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 来管理单例对象的生命周期,这样可以自动释放内存,防止内存泄漏。
  • 删除了拷贝构造函数、赋值运算符以及移动构造函数和移动赋值运算符来禁止复制或移动单例对象。
相关推荐
blasit9 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
七月丶14 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞14 小时前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼14 小时前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟1 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder1 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
肆忆_1 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
阿星AI工作室2 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding