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;