C++单例模式的设计

单例模式(Singleton Pattern)是一种设计模式,用于确保一个类只有一个实例,并提供一个全局访问点来访问该实例。在C++中,单例模式通常用于管理全局资源或共享状态。

以下是C++中实现单例模式的几种常见方式:

  1. 懒汉式(Lazy Initialization)
    懒汉式单例在第一次使用时才创建实例。

非线程安全版本:

cpp 复制代码
class Singleton {
public:
    static Singleton& getInstance() {
        if (!instance) {
            instance = new Singleton();
        }
        return *instance;
    }

    // 删除拷贝构造函数和赋值运算符
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

private:
    Singleton() {}  // 私有构造函数
    ~Singleton() {} // 私有析构函数

    static Singleton* instance; // 静态实例指针
};

Singleton* Singleton::instance = nullptr; // 初始化静态成员

线程安全版本(使用双重检查锁定):

cpp 复制代码
#include <mutex>

class Singleton {
public:
    static Singleton& getInstance() {
        if (!instance) {
            std::lock_guard<std::mutex> lock(mutex);
            if (!instance) {
                instance = new Singleton();
            }
        }
        return *instance;
    }

    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

private:
    Singleton() {}
    ~Singleton() {}

    static Singleton* instance;
    static std::mutex mutex;
};

Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mutex;
  1. 饿汉式(Eager Initialization)
    饿汉式单例在程序启动时即创建实例,线程安全。
cpp 复制代码
class Singleton {
public:
    static Singleton& getInstance() {
        static Singleton instance; // 静态局部变量,程序启动时初始化
        return instance;
    }

    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

private:
    Singleton() {}
    ~Singleton() {}
};
  1. Meyer's Singleton(静态局部变量)
    这是C++中最简洁的单例实现方式,利用了静态局部变量的特性(线程安全且懒加载)。
cpp 复制代码
class Singleton {
public:
    static Singleton& getInstance() {
        static Singleton instance; // 静态局部变量,线程安全且懒加载
        return instance;
    }

    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

private:
    Singleton() {}
    ~Singleton() {}
};
相关推荐
肆忆_17 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星21 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1235 天前
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