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 来管理单例对象的生命周期,这样可以自动释放内存,防止内存泄漏。
  • 删除了拷贝构造函数、赋值运算符以及移动构造函数和移动赋值运算符来禁止复制或移动单例对象。
相关推荐
承渊政道18 分钟前
【优选算法】(实战体会位运算的逻辑思维)
数据结构·c++·笔记·学习·算法·leetcode·visual studio
m0_7167652344 分钟前
C++提高编程--STL常用容器(set/multiset、map/multimap容器)详解
java·开发语言·c++·经验分享·学习·青少年编程·visual studio
承渊政道1 小时前
【优选算法】(实战推演模拟算法的蕴含深意)
数据结构·c++·笔记·学习·算法·leetcode·排序算法
朽棘不雕1 小时前
c++中为什么new[]和delete[]要配对使用
c++
elseif1232 小时前
出题团招人
c++
不想写代码的星星2 小时前
SFINAE 的演进:从替换失败不是错误,到 Concepts 的优雅
c++
2401_878530213 小时前
自定义内存布局控制
开发语言·c++·算法
leaves falling3 小时前
C++模板初阶:让代码“复制粘贴”自动化
开发语言·c++·自动化
2301_816651223 小时前
C++模块化设计原则
开发语言·c++·算法
Yu_Lijing4 小时前
基于C++的《Head First设计模式》笔记——备忘录模式
c++·笔记·设计模式·备忘录模式