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;
相关推荐
workflower3 小时前
单元测试-例子
java·开发语言·算法·django·个人开发·结对编程
YuanlongWang3 小时前
C# 基础——装箱和拆箱
java·开发语言·c#
b78gb3 小时前
电商秒杀系统设计 Java+MySQL实现高并发库存管理与订单处理
java·开发语言·mysql
LXS_3575 小时前
Day 05 C++ 入门 之 指针
开发语言·c++·笔记·学习方法·改行学it
etsuyou6 小时前
js前端this指向规则
开发语言·前端·javascript
shizhenshide6 小时前
为什么有时候 reCAPTCHA 通过率偏低,常见原因有哪些
开发语言·php·验证码·captcha·recaptcha·ezcaptcha
挂科是不可能出现的6 小时前
最长连续序列
数据结构·c++·算法
mit6.8246 小时前
[Agent可视化] 配置系统 | 实现AI模型切换 | 热重载机制 | fsnotify库(go)
开发语言·人工智能·golang
友友马6 小时前
『 QT 』QT控件属性全解析 (一)
开发语言·前端·qt
小白学大数据7 小时前
实战:Python爬虫如何模拟登录与维持会话状态
开发语言·爬虫·python