两种单例模式

双重检查锁(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;
}
相关推荐
一点多余.8 天前
java中的单例模式
java·开发语言·单例模式
NaCl鱼呜啦啦9 天前
static 实例 vs 单例模式
开发语言·单例模式
白太岁10 天前
C++:(5) 单例模式与支持初始化失败的单例模式
c++·单例模式
A懿轩A11 天前
【Java 基础编程】Java 面向对象进阶:static/final、抽象类、接口、单例模式
java·开发语言·单例模式
郝学胜-神的一滴11 天前
单例模式:从经典实现到Vibe Coding时代的思考
开发语言·c++·程序人生·单例模式·设计模式·多线程
Andy Dennis12 天前
各种单例模式的实现方式
java·单例模式
逆境不可逃12 天前
【从零入门23种设计模式02】创建型之单例模式(5种实现形式)
java·spring boot·后端·单例模式·设计模式·职场和发展
百锦再14 天前
线程安全的单例模式全方位解读:从原理到最佳实践
java·javascript·安全·spring·单例模式·kafka·tomcat
柴郡猫乐园17 天前
JDK中一个单例模式的实现
java·开发语言·单例模式
HEU_firejef17 天前
设计模式——单例模式
单例模式·设计模式