(1)单例类模板
template <typename T>
class Singleton
{
static std::once_flag flag;
static T* c_instance;
static void init()
{
if (c_instance == NULL)
{
c_instance = new T();
}
}
public:
static T* GetInstance()
{
std::call_once(flag, &Singleton::init);//保证只被调用一次 特别在多线程中
return c_instance;
}
~Singleton()
{
if (c_instance)
{
delete c_instance;
c_instance = NULL;
}
}
};
template <typename T>
T* Singleton<T>::c_instance = NULL;
template <typename T>
std::once_flag Singleton<T>::flag;
(2)单例类模板引用
class CSingleton
{
friend class Singleton<CSingleton>;
private:
CSingleton() {};
CSingleton(const CSingleton&) = delete;
CSingleton& operator=(const CSingleton&) = delete;
public:
void print();
};
(3)实例化
Singleton<CSingleton>::GetInstance()->print();