C++设计模式 单例模式

单例模式是一种常用的软件设计模式,它保证一个类只有一个实例,并提供一个全局访问点。下面是一个使用 C++11 特性编写的线程安全的单例模式示例:

cpp 复制代码
#include <iostream>
#include <mutex> // For thread safety
#include <memory>

class Singleton {
public:
    static Singleton& getInstance() {
        std::call_once(initInstanceFlag, &Singleton::initSingleton);
        return *instance;
    }

    void doSomething() {
        std::cout << "Doing something useful.\n";
    }

public:

    // Prevent move constructor and move assignment operator from being used
    Singleton(Singleton&&) = delete;
    Singleton& operator=(Singleton&&) = delete;

    Singleton() {} // Constructor is private

    static void initSingleton() {
        instance = std::make_unique<Singleton>();
    }


    // Disable copy constructor and assignment operator
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

private:
    static std::unique_ptr<Singleton> instance;
    static std::once_flag initInstanceFlag;

};

// Initialize static members
std::unique_ptr<Singleton> Singleton::instance = nullptr;
std::once_flag Singleton::initInstanceFlag;

int main() {
    Singleton& s = Singleton::getInstance();
    s.doSomething();

    return 0;
}

在这个例子中:

  • getInstance() 是一个静态成员函数,用于获取 Singleton 类的唯一实例。它使用了 std::call_once 来确保只初始化一次,并且在多线程环境下是安全的。
  • doSomething() 是一个示例功能函数。
  • 使用了 std::unique_ptr 来管理单例对象的生命周期,这样可以自动释放内存,防止内存泄漏。
  • 删除了拷贝构造函数、赋值运算符以及移动构造函数和移动赋值运算符来禁止复制或移动单例对象。
相关推荐
Univin1 小时前
C++(10.5)
开发语言·c++·算法
AA陈超1 小时前
虚幻引擎UE5专用服务器游戏开发-33 在上半身播放组合蒙太奇
c++·游戏·ue5·游戏引擎·虚幻
qq_428639611 小时前
虚幻基础:组件间的联动方式
c++·算法·虚幻
@大迁世界2 小时前
Vue 设计模式 实战指南
前端·javascript·vue.js·设计模式·ecmascript
怎么没有名字注册了啊2 小时前
C++后台进程
java·c++·算法
slim~3 小时前
CLion实现ini 解析器设计与实现
c++·后端·clion
AA陈超4 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-05 游戏效果委托
c++·游戏·ue5·游戏引擎·虚幻
杨小码不BUG4 小时前
Davor的北极探险资金筹集:数学建模与算法优化(洛谷P4956)
c++·算法·数学建模·信奥赛·csp-j/s
mit6.8244 小时前
10.5 数位dp
c++·算法
初圣魔门首席弟子4 小时前
C++ STL 向量(vector)学习笔记:从基础到实战
c++·笔记·学习