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 来管理单例对象的生命周期,这样可以自动释放内存,防止内存泄漏。
  • 删除了拷贝构造函数、赋值运算符以及移动构造函数和移动赋值运算符来禁止复制或移动单例对象。
相关推荐
卡提西亚14 分钟前
C++笔记-10-循环语句
c++·笔记·算法
亮剑201844 分钟前
第1节:C语言初体验——环境、结构与基本数据类型
c++
William_wL_1 小时前
【C++】类和对象(下)
c++
William_wL_2 小时前
【C++】内存管理
c++
星星火柴9362 小时前
笔记 | C++面向对象高级开发
开发语言·c++·笔记·学习
悲伤小伞3 小时前
Linux_Socket_UDP
linux·服务器·网络·c++·网络协议·udp
八个程序员3 小时前
自定义函数(C++)
开发语言·c++·算法
乐悠小码4 小时前
Java设计模式精讲---02抽象工厂模式
java·设计模式·抽象工厂模式
微露清风5 小时前
系统性学习C++-第十讲-stack 和 quene
java·c++·学习
报错小能手5 小时前
C++笔记(面向对象)静态联编和动态联编
开发语言·c++·算法