1 #ifndef _SINGLETON_H_ 2 #define _SINGLETON_H_ 3 4 #include <mutex> 5 #include <memory> 6 7 template<typename T> 8 class Singleton { 9 public: 10 template <typename... ArgTypes> 11 static T* getInstance(ArgTypes... args) { 12 static std::once_flag of; 13 std::call_once(of, init(std::forward<Args>(args)...)); 14 15 return instance_.get(); 16 } 17 private: 18 Singleton() = delete; 19 ~Singleton() = delete; 20 Singleton(const Singleton&) = delete; 21 Singleton(Singleton&&) = delete; 22 Singleton& operator=(const Singleton&) = delete; 23 Singleton& operator=(Singleton&&) = delete; 24 25 template <typename... ArgTypes> 26 static void init(ArgTypes... args) { 27 instance_.reset(new T(std::forward<ArgTypes>(args)...)); 28 } 29 30 static std::unique_ptr<T> instance_; 31 }; 32 33 template<class T> 34 std::unique_ptr<T> Singleton<T>::instance_ = nullptr; 35 36 #endif
原文地址:https://www.cnblogs.com/CodeComposer/p/9485037.html
时间: 2024-11-05 22:50:53