要求
- 构造函数应该私有
- 构造出的对象由类保存
- 提供接口能让外界访问带对象
- 考虑多线程。
- 按需创建
如果按需创建,那么需要避免多线程同时访问“没有实例”,然后都去创建实例。
因此,如果是按需创建应该是
class Singleton
{
private:
Singleton();
static Singleton *instance;
public:
Singleton &get_instance()
{
if(instance == nullptr)
{
MutexLock_guard lock(mutex);
if(instance == nullptr)
{
instance = new Singleton;
}
}
return *instance;
}
}
如果不需要按需创建,那么直接定义一个私有的静态成员
private:
static Singleton *instance = new Singleton;
就可以了。