我認爲最優雅的C++單例類寫法

class Singleton
{
public:
    static Singleton  &instance() {
        static Singleton singleton;
	    return singleton;
	}
    Singleton (Singleton &&) = delete;
    Singleton (Singleton  const&) = delete;

private:
    Singleton() = default;
};

其中的要點:

  1. 通過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.

  2. 刪除複製構造函數和移動構造函數。 不需要管複製操作符重載的情況,因爲產生一個新的對象時一定有構造函數被調用。

  3. 將需要使用的構造函數定義爲private。如果構造函數中不需要代碼,可以直接賦default

使用方法

Singleton  &singleton = Singleton ::instance();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章