一个基于C++11的单例模板类

时间:2022-01-15 10:56:37

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

template<typename T>
class Singleton : public Uncopyable {
public:
template <typename... ArgTypes>
static T* getInstance(ArgTypes... args) {
static std::once_flag of;
std::call_once(of, [&]() { Singleton::instance_.reset(new T(std::forward<ArgTypes>(args)...)); });

return instance_.get();
}
private:
static std::unique_ptr<T> instance_;
};

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

#endif