c++ 单例模式模板类

//
// Created by 51bitquant on 2023/3/19.
//

ifndef IO_SINGLETON_H

define IO_SINGLETON_H

include <cstdlib>

template <typename T>
class Singleton {
public:
static T& getSingleton() {
if(!instance_.get()) {
instance_ = std::unique_ptr<T>(new T);
}
return *(instance_.get());
}
private:
static std::unique_ptr<T> instance_;
Singleton();
Singleton(const Singleton<T> & other);
Singleton & operator=(const Singleton<T> & other);

};

template <typename T>
std::unique_ptr<T> Singleton<T>::instance_ = nullptr;

template <typename T>
class Singleton1 {
public:
static T& getSingleton() {
init();
return instance_;
}
private:
static void init() {
if (instance_ == nullptr) {
instance_ = new T;
atexit(destroy);
}
}
static void destroy() {
delete instance_;
}
static T
instance_;
Singleton1();
Singleton1(const Singleton<T> & other);
Singleton1 & operator=(const Singleton<T> & other);

};

template <typename T>
T* Singleton1<T>::instance_ = nullptr;

endif //IO_SINGLETON_H

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容