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;
相关推荐
肆忆_16 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星20 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20215 天前
信号量和信号
linux·c++
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc