单例模式两种实现方法

设计模式

单例模式:

复制代码
#include <iostream>
#include<mutex>

class MyCAS {
private:
  MyCAS() {};
  MyCAS(const MyCAS*) = delete;
  MyCAS& operator=(const MyCAS*) = delete;
private:
  static MyCAS* m_instance;
  static std::mutex m_mutex;

public:

  static MyCAS* GetInstance() {
    if (m_instance == nullptr) {
      std::lock_guard<std::mutex> lock(m_mutex);
      if (m_instance == nullptr) {
        m_instance = new MyCAS();
        static CGarhuishou cl;
      }

    }
    return m_instance;
  };

  class CGarhuishou {
  public:
    ~CGarhuishou() {
      if (MyCAS::m_instance) {
        delete MyCAS::m_instance;
        MyCAS::m_instance = nullptr;
      }
    }
  };
  void func() {
    std::cout << "测试" << std::endl;
  }
};
MyCAS* MyCAS::m_instance = nullptr;
std::mutex MyCAS::m_mutex;

使用std::once_flag ,作为一个标记,std::call_once通过这个标记来决定对应传入的函数是否执行,调用call_once成功后,call_once会反转这个标记,这样再次调用这个call_once后,传入的函数就不会再次被执行了;

复制代码
#include <iostream>
#include<mutex>

class MyCAS {
private:
  MyCAS() {};
  MyCAS(const MyCAS*) = delete;
  MyCAS& operator=(const MyCAS*) = delete;
private:
  static MyCAS* m_instance;

  static std::once_flag m_flag;
public:
  static void CreateInstance() {
    m_instance = new MyCAS();
    static CGarhuishou cl;
  }
  static MyCAS* GetInstance() {

    std::call_once(m_flag, CreateInstance);

    return m_instance;
  };

  class CGarhuishou {
  public:
    ~CGarhuishou() {
      if (MyCAS::m_instance) {
        delete MyCAS::m_instance;
        MyCAS::m_instance = nullptr;
      }
    }
  };
  void func() {
    std::cout << "测试" << std::endl;
  }
};
MyCAS* MyCAS::m_instance = nullptr;

std::once_flag MyCAS::m_flag;
相关推荐
ShineWinsu11 小时前
对于C++:auto_ptr、unique_ptr、shared_ptr的模拟实现
c++·面试·笔试·智能指针·unique_ptr·shared_ptr·auto_ptr
hsjiasb11 小时前
FreeRTOS学习(二十七)——任务栈与栈溢出检测
开发语言·stm32·学习·学习笔记·freertos
丰锋ff12 小时前
3.1 Qt事件之事件处理器
开发语言·qt
多弗朗皮卡丘12 小时前
C语言梦开始的地方7:函数
c语言·开发语言
月华路13 小时前
G1 垃圾回收:脏卡队列、记忆集与并发精化线程机制
java·开发语言
XLYcmy13 小时前
京东 算法实习一面 下+手撕
c++·python·llm·概率论·数据处理·训练·codebert
gugucoding13 小时前
47. 【Java】Java内存模型(JMM)与可见性
java·开发语言
m0_3807438713 小时前
从零调用 Claude 教程
开发语言·python·node.js
起床学FPGA13 小时前
AI回答问题之后,会自动跳到最下面的问题
开发语言·javascript·ecmascript
反转180度14 小时前
Qt 6 + C++17 实现 SFTP 批量部署:工业设备运维工具实战解析
运维·c++·qt