
C++——单例模式
最近碰到一道题: 如何定义一个单例类?
class Singleton{
public:
static Singleton* GetInstance(){
return &m_instance;
}
private:
// 构造函数私有
Singleton(){};
// C++98 防拷贝
Singleton(Singleton const&);
Singleton& operator=(Singleton const&);
// or
// C++11
Singleton(Singleton const&) = delete;
Singleton& operator=(Singleton const&) = delete;
static Singleton m_instance;
};
Singleton Singleton::m_instance = new Singleton; // 在程序入口之前就完成单例对象的初始化
主要思想就是将构造和拷贝构造函数设成私有,然后将类提前用static定义一个自己类型的对象,并在类外进行初始化。这种方法称为饿汉模式,不管是否使用,都将创建这个类。
