#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特性:这样保证了并发线程在获取静态局部变量的时候一定是初始化过的,所以具有线程安全性。
这篇博客介绍了C++11中使用Meyers Singleton实现线程安全的单例模式。通过静态局部变量和删除拷贝构造函数与赋值操作符,确保了在多线程环境下单例实例的唯一性和线程安全。Meyers的单例方法利用C++11的Magic Static特性,使得在并发环境中初始化静态局部变量时不会引发竞态条件。
744

被折叠的 条评论
为什么被折叠?



