#include <iostream>
class Singleton
{
public:
~Singleton(){
std::cout<<"destructor called!"<<std::endl;
}
//析构函数=delete。这个c++11的新写法。代表该函数为删除函数,也就是不能重载,不会被调用。
//这类函数可以声明,但是没有定义。编译器会阻止对它们进行定义。
Singleton(const Singleton&)=delete;
Singleton& operator=(const Singleton&)=delete;
static Singleton& get_instance(){
static Singleton instance;
return instance;
}
private:
Singleton(){
std::cout<<"constructor called!"<<std::endl;
}
};
int main(int argc, char *argv[])
{
Singleton& instance_1 = Singleton::get_instance();
Singleton& instance_2 = Singleton::get_instance();
return 0;
}
运行结果
constructor called!
destructor called!
这种方法又叫做 Meyers' SingletonMeyer's的单例, 是著名的写出《Effective C++》系列书籍的作者 Meyers 提出的。所用到的特性是在C++11标准中的Magic Static特性:这样保证了并发线程在获取静态局部变量的时候一定是初始化过的,所以具有线程安全性。