#ifndef __SINGLETON__H_
#define __SINGLETON__H_
template <class T>
class singleton
{
public:
static T* Instance()
{
static T s_instance;
return &s_instance;
}
};
#endif
#ifndef __SINGLETON__H_
#define __SINGLETON__H_
#include "CMutex.h"
#define SINGLE_CLASS_INITIAL(TypeName) private:\
TypeName();\
friend class CSingleton<TypeName>
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
TypeName& operator=(const TypeName&)
template <typename T>
class CSingleton
{
public:
static T* Instance();
virtual ~CSingleton(){};
protected:
CSingleton(){};
private:
class CGarbo //它的唯一工作就是在析构函数中删除CSingleton的实例
{
public:
~CGarbo()
{
if (nullptr != CSingleton::m_pInstance)
{
delete CSingleton::m_pInstance;
CSingleton::m_pInstance = nullptr;
}
}
};
private:
DISALLOW_COPY_AND_ASSIGN(CSingleton);
static T* m_pInstance;
static CGarbo m_cGarbo; //定义一个静态成员变量,程序结束时,系统会自动调用它的析构函数
static CMutex m_cStaticMutex;
};
template <typename T>
T* CSingleton<T>::m_pInstance = nullptr;
template <typename T>
CMutex CSingleton<T>::m_cStaticMutex;
//template <typename T>
//CSingleton<typename>::CGarbo CSingleton<T>::m_cGarbo;
template <typename T>
T* CSingleton<T>::Instance()
{
if (nullptr == m_pInstance)
{
m_cStaticMutex.Lock();
while (nullptr == m_pInstance)
{
m_pInstance = new T();
}
m_cStaticMutex.UnLock();
}
return m_pInstance;
}
#endif