使用c11的std::call_once实现饿汉模式的单例模板
#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() { std::once_flag sflag; std::call_once(sflag, [&](){ instance.reset(new T()); }); return *instance; } #define SINGLETON(Class) \ public: \ ~Class() = default; \ private: \ Class() = default; \ Class(const Class &other) = delete; \ Class& operator=(const Class &other) = delete; \ friend class Singleton<Class>; \ #endif // SINGLETON_H
来源:https://www.cnblogs.com/vczf/p/12600251.html