最方便常用的是Meyers' Singleton,多线程安全。gcc 4.0之后的编译器支持这种写法,要求C++11及其以后的版本。
class Singleton
{
public:
// 注意返回的是引用
static Singleton &getInstance()
{
static Singleton instance; // 静态局部变量
return instance;
}
private:
Singleton() = default;
Singleton(const Singleton &) = delete; // 禁用拷贝构造函数
Singleton &operator=(const Singleton &) = delete; // 禁用拷贝赋值运算符
};
完整的验证程序:
#include <iostream>
using namespace std;
class Singleton
{
public:
// 注意返回的是引用
static Singleton &getInstance()
{
static Singleton instance; // 静态局部变量
return instance;
}
private:
Singleton() = default;
Singleton(const Singleton &) = delete; // 禁用拷贝构造函数
Singleton &operator=(const Singleton &) = delete; // 禁用拷贝赋值运算符
};
int main()
{
Singleton& s1 = Singleton::getInstance(); // &是引用
cout << &s1 << endl; // &是取地址
Singleton& s2 = Singleton::getInstance();
cout << &s2 << endl;
// Singleton s3(s1);
// s2 = s1;
system("pause");
return 0;
}
打印出s1和s2的地址是同一个,因为是同一个静态局部变量。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。