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 来管理单例对象的生命周期,这样可以自动释放内存,防止内存泄漏。
  • 删除了拷贝构造函数、赋值运算符以及移动构造函数和移动赋值运算符来禁止复制或移动单例对象。
相关推荐
blueman88881 小时前
Qt5通过vcpkg中调用时,在debug模式下调试时总是调用release的plugins文件夹中的dll
c++·qt·cmake
jinyishu_4 小时前
C++ string使用方法
开发语言·c++
乐观勇敢坚强的老彭5 小时前
C++浮点数使用注意事项
开发语言·c++
库克克5 小时前
【C++ 】内联函数
java·开发语言·c++
盐焗鹌鹑蛋5 小时前
【C++】红黑树
c++
aaPIXa6227 小时前
C++采样引导优化SPGO——比PGO更智能的编译器决策新方案
java·c++·人工智能
Starmoon_dhw8 小时前
题解:P17078 夏日甜点
c++·学习·算法·图论
某不知名網友8 小时前
C/C++动态内存管理,智能指针及RAlI思想。
java·c语言·c++
hold?fish:palm9 小时前
从源码到可执行文件:C++程序的编译过程
开发语言·c++
lingran__9 小时前
C++_STL简介
开发语言·c++