class Singleton
{
public:
static Singleton &instance() {
static Singleton singleton;
return singleton;
}
Singleton (Singleton &&) = delete;
Singleton (Singleton const&) = delete;
private:
Singleton() = default;
};
其中的要点:
-
通过static局部变量定义唯一对象, 在C++11中,不再需要手动加锁保证线程安全。C++ working paper这样描述的:
If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.
-
删除复制构造函数和移动构造函数。 不需要管复制操作符重载的情况,因为产生一个新的对象时一定有构造函数被调用。
-
将需要使用的构造函数定义为
private
。如果构造函数中不需要代码,可以直接赋default
。
使用方法
Singleton &singleton = Singleton ::instance();