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();