C++代码如下:
#include <iostream>
using std::cout;
using std::endl;
//懒汉式
class SingletonLazy{
public:
static SingletonLazy& getinstance(){
static SingletonLazy m_instance;
return m_instance;
}
public:
SingletonLazy(const SingletonLazy&) = delete;//禁止拷贝构造函数的调用
SingletonLazy(SingletonLazy&&) = delete;//禁止移动构造函数的调用
SingletonLazy& operator=(const SingletonLazy&) = delete;//禁止拷贝赋值操作符的调用
SingletonLazy& operator=(SingletonLazy&&) = delete;//禁止移动赋值操作符的调用
private:
SingletonLazy(){
cout<<"ConstructorLazy called"<<endl;
}
~SingletonLazy(){
cout<<"DestructorLazy called"<<endl;
}
};
//饿汉式
class SingletonHungry{
public:
static SingletonHungry& getinstance(){
return m_instance;
}
public:
SingletonHungry(const SingletonHungry&) = delete;
SingletonHungry(SingletonHungry&&) = delete;
SingletonHungry& operator=(const SingletonHungry&) = delete;
SingletonHungry& operator=(SingletonHungry&&) = delete;
private:
static SingletonHungry m_instance;
SingletonHungry(){
cout<<"ConstructorHungry called"<<endl;
}
~SingletonHungry(){
cout<<"DestructorHungry called"<<endl;
}
};
SingletonHungry SingletonHungry::m_instance;
int main(){
SingletonLazy& instance_1=SingletonLazy::getinstance();
SingletonHungry& instance_2=SingletonHungry::getinstance();
return 0;
}
代码解释:
由于在main函数之前初始化,所以没有线程安全的问题。但是潜在问题在于no-local static对象(函数外的static对象)在不同编译单元中的初始化顺序是未定义的。也即,static Singleton m_instance;和static Singleton& getInstance()⼆者的初始化顺序不确定,如果在初始化完成之前调⽤ getInstance() ⽅法会返回⼀个未定义的实例。
这是最推荐的一种单例实现方式:
1.通过局部静态变量的特性保证了线程安全 (C++11, GCC > 4.3, VS2015支持该特性)。
2.不需要使用共享指针,代码简洁,不需要使用互斥锁,没有双重检查锁定模式的风险。
3.注意在使用的时候需要声明单例的引用 SingletonPattern_V3& 才能获取对象。
运行结果:
ConstructorHungry called
ConstructorLazy called
DestructorLazy called
DestructorHungry called
分析运行结果:
1.ConstructorHungry called:饿汉式单例在类加载时初始化。
2.ConstructorLazy called:懒汉式单例在第一次调用 getinstance() 时初始化。
3.DestructorLazy called 和 DestructorHungry called:析构函数按照与构造函数相反的顺序被调用。