饿汉模式单例模板
使用c11的std::call_once实现饿汉模式的单例模板
- 析构私有,default_delete需要加入友元
- 构造函数没有默认,有时候需要在构造函数里初始化数据
#ifndef SINGLETON_H #define SINGLETON_H #include <memory> #include <mutex> //单例模板 template <typename T> class Singleton { public: static T& GetInstance(); private: static std::unique_ptr<T> instance; }; template <typename T> std::unique_ptr<T> Singleton<T>::instance; template <typename T> T& Singleton<T>::GetInstance() { static std::once_flag sflag; std::call_once(sflag, [&](){ instance.reset(new T()); }); return *instance; } #define SINGLETON(Class) \ private: \ ~Class() = default; \ Class(const Class &other) = delete; \ Class& operator=(const Class &other) = delete; \ friend class Singleton<Class>; \ friend struct std::default_delete<Class>; #endif // SINGLETON_H
使用:
#include "Singleton.h" #define Test_T Singleton<Test>::GetInstance() class Test { SINGLETON(LogMgr) private: Test() = default; }