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;
相关推荐
SmartRadio6 小时前
CH585M+MK8000、DW1000 (UWB)+W25Q16的低功耗室内定位设计
c语言·开发语言·uwb
rfidunion6 小时前
QT5.7.0编译移植
开发语言·qt
rit84324996 小时前
MATLAB对组合巴克码抗干扰仿真的实现方案
开发语言·matlab
微露清风6 小时前
系统性学习C++-第十八讲-封装红黑树实现myset与mymap
java·c++·学习
大、男人6 小时前
python之asynccontextmanager学习
开发语言·python·学习
hqwest7 小时前
码上通QT实战08--导航按钮切换界面
开发语言·qt·slot·信号与槽·connect·signals·emit
CSARImage7 小时前
C++读取exe程序标准输出
c++
一只小bit7 小时前
Qt 常用控件详解:按钮类 / 显示类 / 输入类属性、信号与实战示例
前端·c++·qt·gui
AC赳赳老秦7 小时前
DeepSeek 私有化部署避坑指南:敏感数据本地化处理与合规性检测详解
大数据·开发语言·数据库·人工智能·自动化·php·deepseek
一条大祥脚7 小时前
26.1.9 轮廓线dp 状压最短路 构造
数据结构·c++·算法