C++ | 单例模式
为什么会有单例模式?
通常都会举Windows的任务管理器的栗子。
单例模式怎么实现呢?
1 #include <memory> 2 #include <iostream> 3 using namespace std; 4 5 class Singleton 6 { 7 public: 8 static Singleton * Instance() { 9 if( 0== _instance.get()) { 10 _instance.reset( new Singleton); 11 } 12 return _instance.get(); 13 } 14 15 protected: 16 Singleton(void) { 17 cout <<"Create Singleton"<<endl; 18 } 19 20 virtual ~Singleton(void) { 21 cout << "Destroy Singleton"<<endl; 22 } 23 24 friend class auto_ptr<Singleton>; 25 26 static auto_ptr<Singleton> _instance; 27 28 }; 29 30 auto_ptr<Singleton> Singleton::_instance; //cpp file
上面的类不是线程安全的。可以考虑在new的时候上锁,new完后解锁。或更高效的静态化初始化。
waiting to write……
http://www.jellythink.com/archives/82