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

Singleton单例模式--C++实现

2015-06-03 21:39 323 查看
1. 只支持单线程 (不推荐)

#include <iostream>
using namespace std;

class Singleton
{
public:
static Singleton* getInstance();//<1>必须是static,这样才可以通过类名访问。
private:
static Singleton* _instance;//<2>必须是static,这样生存期才是全局的。
Singleton();//<3>必须是private,这样就不能通过构造函数来实例化。
};

Singleton* Singleton::getInstance()
{
if (_instance == NULL)
{
_instance = new Singleton();
}
return _instance;
}
Singleton* Singleton::_instance = NULL;//static变量必须初始化
Singleton::Singleton()    //构造函数既然要用到,而且类内部也声明了,就必须给出定义才能用。
{
cout << "success" << endl;
}

int main()
{
Singleton* sgt = Singleton::getInstance();
}


View Code

reference[1]将代码分成了Singleton.h, Singleton.cpp和main.cpp三个文件来实现,回顾一下文件组织。

2. 多线程 (通用)

class Singleton
{
public:
static Singleton* GetInstance()
{
static Singleton instance;
return &instance;
}

private:
Singleton() {}                              // ctor hidden
Singleton(const Singleton& s);            // copy ctor hidden
Singleton& operator=(const Singleton& s); // assign op. hidden
};


C++11后使用static是线程安全的。

“If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.”

当一个线程正在初始化一个变量的时候,其他线程必须得等到该初始化完成以后才能访问它。

不想让一个类被隐式或显式地构造,就把它的构造函数和big three(拷贝构造函数,重载赋值运算符,析构函数)给定义成private并且只声明不实现。这样别人就没法来用了。

否则的话,编译器会自动为它生成构造函数和big three。

reference:

[1] http://ccftp.scu.edu.cn:8090/Download/038c70a8-c724-4b86-91c3-74b927b1d492.pdf
[2] http://www.cnblogs.com/bigwangdi/p/3139831.html
[3] http://liyuanlife.com/blog/2015/01/31/thread-safe-singleton-in-cxx/
[4] http://blog.sina.com.cn/s/blog_6ce9e8870101i1cz.html
[5] http://wuchong.me/blog/2014/08/28/how-to-correctly-write-singleton-pattern/#
[6] http://blog.csdn.net/crayondeng/article/details/24853471
[7] http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
[8] http://blog.csdn.net/dragoncheng/article/details/2781#t4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: