您的位置:首页 > 编程语言 > C语言/C++

C++ | 单例模式

2015-09-26 00:13 411 查看
为什么会有单例模式?

通常都会举Windows的任务管理器的栗子。

单例模式怎么实现呢?

#include <memory>
#include <iostream>
using namespace std;

class Singleton
{
public:
static Singleton * Instance() {
if( 0== _instance.get()) {
_instance.reset( new Singleton);
}
return _instance.get();
}

protected:
Singleton(void) {
cout <<"Create Singleton"<<endl;
}

virtual ~Singleton(void) {
cout << "Destroy Singleton"<<endl;
}

friend class auto_ptr<Singleton>;

static auto_ptr<Singleton> _instance;

};

auto_ptr<Singleton> Singleton::_instance;    //cpp file


上面的类不是线程安全的。可以考虑在new的时候上锁,new完后解锁。或更高效的静态化初始化。

waiting to write……
http://www.jellythink.com/archives/82
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: