auto_ptr for singleton pattern
时间:2011-02-19 来源:DoubleTen
1 #ifndef SINGLETON_H_
2 #define SINGLETON_H_
3 #include <memory>
4 class Singleton {
5 private:
6 Singleton();
7 static std::auto_ptr<Singleton> apSingle;
8 public:
9 virtual ~Singleton();
10 void func();
11 static Singleton& instance();
12 };
13 #endif /* SINGLETON_H_ */
Singleton.cpp中实现
1 #include <iostream>
2 #include <memory>
3 #include "Singleton.h"
4 std::auto_ptr<Singleton> Singleton::apSingle;
5 void Singleton::func(){
6 std::cout << "in func" << std::endl;
7 }
8 Singleton::Singleton(){
9 // TODO Auto-generated constructor stub
10 std::cout << "in con" << std::endl;
11 }
12 Singleton::~Singleton() {
13 // TODO Auto-generated destructor stub
14 std::cout << "in decon" << std::endl;
15 }
16 Singleton& Singleton::instance(){
17 if(apSingle.get() == NULL){
18 apSingle.reset(new Singleton());
19 }
20 return *apSingle;
21 }
相关阅读 更多 +