C++单例模式

前言

C++中的单例模式(Singleton Pattern)是一种常用的软件设计模式,用于确保一个类只有一个实例,并提供一个全局访问点来获取这个实例。单例模式通常用于管理共享资源,如配置信息、线程池、缓存等。

一、懒汉式单例

复制代码
class Singleton {
private:
    Singleton() {} // 私有构造函数

public:
    static Singleton& getInstance() {
        static Singleton instance; // 局部静态变量
        return instance;
    }
};

懒汉式单例在第一次使用时才创建实例

二、饱汉式单例

复制代码
class Singleton {
private:
    static Singleton instance; // 静态实例

    Singleton() {} // 私有构造函数

public:
    static Singleton& getInstance() {
        return instance;
    }
};

// 实现静态成员变量
Singleton Singleton::instance;

饿汉式单例在程序启动时就创建实例,这保证了线程安全,但可能会增加启动时间。

三、使用智能指针

复制代码
#include <memory>
#include <mutex>

class Singleton {
private:
    static std::shared_ptr<Singleton> instance;
    static std::mutex mutex;
    Singleton() {} // 私有构造函数

public:
    static std::shared_ptr<Singleton> getInstance() {
        if (instance == nullptr) {
            std::lock_guard<std::mutex> lock(mutex);
            if (instance == nullptr) {
                instance = std::make_shared<Singleton>();
            }
        }
        return instance;
    }
};

// 初始化静态成员变量
std::shared_ptr<Singleton> Singleton::instance = nullptr;
std::mutex Singleton::mutex;
相关推荐
小七在进步2 小时前
string的使用(1)
c++·visual studio
SomeOtherTime2 小时前
Rust所有权(AI回答)
开发语言·后端·rust
Easyhood2 小时前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
白杨尚青3 小时前
C++进阶篇(六):map 和 set 的模拟实现——用红黑树封装 mymap/myset(迭代器 + operator[])
开发语言·c++·迭代器·stl·set·map·红黑树
kloc6 小时前
聊天室项目入口网关子服务的实现
linux·c++
饮水桶_T7 小时前
JAVA IO流笔记
开发语言·数据结构·算法
csdn_aspnet9 小时前
C++ 3个有序点的方向(Orientation of 3 ordered points)
c++·算法
Felven9 小时前
C. Brr Brrr Patapim
c语言·开发语言
小七在进步10 小时前
string的使用(2)
c++
路溪非溪10 小时前
python标准库使用总结
开发语言·python