首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++ Singleton 單例模式:懶漢式、線程安全與現代寫法

     編輯:C++ 入門

經典懶漢式(非線程安全)

class Restaurant {
public:
    static Restaurant* getInstance() {
        if (!instance) instance = new Restaurant(100);
        return instance;
    }
    int getSize() { return size; }
    void setSize(int s) { size = s; }
private:
    Restaurant(int s) : size(s) {}
    int size;
    static Restaurant* instance;
};
Restaurant* Restaurant::instance = nullptr;

線程安全版(C++11 靜態局部變量)

C++11 保證靜態局部變量初始化線程安全,且自動析構:

class Restaurant {
public:
    static Restaurant& getInstance() {
        static Restaurant instance(100); // 魔法靜態
        return instance;
    }
    int getSize() { return size; }
    void setSize(int s) { size = s; }
private:
    Restaurant(int s) : size(s) {}
    Restaurant(const Restaurant&) = delete;
    Restaurant& operator=(const Restaurant&) = delete;
    int size;
};

雙重檢查鎖定(DCLP,C++11 前)

static Restaurant* instance = nullptr;
static mutex mtx;
static Restaurant* getInstance() {
    if (!instance) {
        lock_guard lock(mtx);
        if (!instance) instance = new Restaurant(100);
    }
    return instance;
}

關鍵點總結

版本線程安全優點缺點
懶漢式否簡單多線程下可能創建多實例
C++11 靜態局部是標準保證、自動析構、無鎖需 C++11 支持
DCLP是兼容舊標準代碼繁瑣、易寫錯
饿汉式是極簡單程序啟動即構造、可能浪費資源

現代最佳實踐

**首選 C++11 靜態局部變量寫法**:代碼最少、標準保證線程安全、自動管理生命周期、禁止拷貝/移動。
若需延遲初始化且不依賴 C++11,使用 std::call_once 或 DCLP(配合 atomic 和內存序)。

總結

C++ Singleton 核心在於:私有構造、靜態獲取方法、禁止拷貝。現代 C++ 推薦 static T& getInstance() { static T instance; return instance; } 一行解決所有問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved