C++ call_once实现单例模式 懒汉实现 使用内部类、unique_ptr控制析构

Singleton.h

#pragma once
#include <thread>
#include <mutex>

#include <memory>
#include <iostream>

#define THIS_THREAD_COUT(_MESSAGE_) std::cout << std::this_thread::get_id() << ": "<< _MESSAGE_ << std::endl

// 单例模式 懒汉模式 call_once once_flag 内部类控制析构
class Singleton
{
public:
    static Singleton& getInstance()
    {
        call_once(flg, []() {instance = new Singleton(); });
        return *instance;
    }

    int getValue() { return val; }
    void setValue(int _val) { val = _val; }

private:
    //内部类控制析构
    class InnerClazz
    {
    public:
        InnerClazz() { THIS_THREAD_COUT("调用InnerClazz构造函数"); }
        ~InnerClazz() { THIS_THREAD_COUT("调用InnerClazz析构函数"); if(instance) delete instance; }
    };

    Singleton() { THIS_THREAD_COUT("调用Singleton构造函数"); }
    ~Singleton() { THIS_THREAD_COUT("调用Singleton析构函数"); }

    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

private:
    int val = 0;
    static InnerClazz innerInstance;
    static std::once_flag flg;
    static Singleton* instance;
};
// 单例模式 懒汉模式 call_once once_flag unique_ptr控制生命周期【但是单例类析构函数 不能private (自定义删除器?)】
class Singleton_2
{
public:
    static Singleton_2& getInstance()
    {
        call_once(flg, &Singleton_2::init);
        return *instance;
    }

    int getValue() { return val; }
    void setValue(int _val) { val = _val; }

    ~Singleton_2() { THIS_THREAD_COUT("调用Singleton_2析构函数"); }
private:
    Singleton_2() { THIS_THREAD_COUT("调用Singleton_2构造函数"); }
    

    Singleton_2(const Singleton_2&) = delete;
    Singleton_2& operator=(const Singleton_2&) = delete;

private:
    static void init() { instance.reset(new Singleton_2); }

private:
    int val = 0;
    static std::once_flag flg;
    static std::unique_ptr<Singleton_2> instance;
};

Singleton.cpp

#include "Singleton.h"



Singleton::InnerClazz Singleton::innerInstance;
std::once_flag Singleton::flg;
Singleton* Singleton::instance = nullptr;


std::once_flag Singleton_2::flg;
std::unique_ptr<Singleton_2> Singleton_2::instance;

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值