两种单例模式

双重检查锁(DCLP)

  • 通过 std::mutex 保证线程安全
  • 双重检查减少了锁的开销,只有第一次创建时才会加锁
cpp 复制代码
#include <iostream>
#include <mutex>

class Singleton {
private:
    static Singleton* instance;
    static std::mutex mtx;

    // 私有构造函数,禁止外部创建
    Singleton() {
        std::cout << "Constructor called\n";
    }

public:
    // 删除拷贝和赋值,防止拷贝产生多个实例
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

    static Singleton* getInstance() {
        if (instance == nullptr) { // 第一次检查
            std::lock_guard<std::mutex> lock(mtx);
            if (instance == nullptr) { // 第二次检查
                instance = new Singleton();
            }
        }
        return instance;
    }

    void show() {
        std::cout << "Singleton instance address: " << this << "\n";
    }
};

// 静态成员初始化
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;

int main() {
    Singleton* s1 = Singleton::getInstance();
    Singleton* s2 = Singleton::getInstance();

    s1->show();
    s2->show();

    return 0;
}

静态局部变量

  • C++11 标准保证静态局部变量的初始化是线程安全的
  • 不需要手动加锁
cpp 复制代码
#include <iostream>

class Singleton {
private:
    Singleton() {
        std::cout << "Constructor called\n";
    }

public:
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

    static Singleton& getInstance() {
        static Singleton instance; // C++11 保证线程安全
        return instance;
    }

    void show() {
        std::cout << "Singleton instance address: " << this << "\n";
    }
};

int main() {
    Singleton& s1 = Singleton::getInstance();
    Singleton& s2 = Singleton::getInstance();

    s1.show();
    s2.show();

    return 0;
}
相关推荐
白玉cfc7 小时前
【OC】单例模式
开发语言·ios·单例模式·objective-c
T1an-112 小时前
C++版单例模式-现代化简洁写法
c++·单例模式
青草地溪水旁1 天前
设计模式(C++)详解—单例模式(1)
c++·单例模式
库奇噜啦呼1 天前
【iOS】单例模式
ios·单例模式
馨谙1 天前
设计模式之单例模式大全---java实现
java·单例模式·设计模式
土了个豆子的2 天前
04.事件中心模块
开发语言·前端·visualstudio·单例模式·c#
饭碗的彼岸one2 天前
C++设计模式之单例模式
c语言·开发语言·c++·单例模式·设计模式·饿汉模式·懒汉模式
在下雨5993 天前
项目讲解1
开发语言·数据结构·c++·算法·单例模式
TNTLWT3 天前
单例模式(C++)
javascript·c++·单例模式
TT哇3 天前
【多线程案例】:单例模式
java·单例模式·面试