单例模式
#include<memory>
#include<mutex>
template<typename T>
class Singleton{
public:
template<typename... Args>
static std::unique_ptr<T*> instance(Args&&...args)
{
std::call_once(flag_, [&] {
myInstance.reset(new T(std::forward<Args>(args)...));
});
return myInstance;
}
private:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
static std::unique_ptr<Singleton<T*>> myInstance;
static std::once_flag flag_;
};
template<typename T>
std::unique_ptr<Singleton<T*>> Singleton<T>::myInstance = nullptr;
template<typename T>
std::once_flag Singleton<T>::flag_;