#ifndef _SINGLETON_329FC8D0_C954_4cd3_ADE8_B0CB704A35F3_h_
#define _SINGLETON_329FC8D0_C954_4cd3_ADE8_B0CB704A35F3_h_
template<class T>
class Singleton
{
//typedef T ObjectType;
public:
static T & Instance()
{
if(NULL == m_instance)
m_instance = new T;
return *m_instance;
}
protected:
Singleton(){};
private:
static T* m_instance;
};
template<class T>
T* Singleton<T>::m_instance =0;
#define _SINGLETON_329FC8D0_C954_4cd3_ADE8_B0CB704A35F3_h_
template<class T>
class Singleton
{
//typedef T ObjectType;
public:
static T & Instance()
{
if(NULL == m_instance)
m_instance = new T;
return *m_instance;
}
protected:
Singleton(){};
private:
static T* m_instance;
};
template<class T>
T* Singleton<T>::m_instance =0;
#endif
//test
class CPeople
{
public:
int GetAge(){return m_iAge;}
void SetAge(int iAge){m_iAge = iAge;}
protected:
private:
int m_iAge;
};
typedef Singleton<CPeople> singleMgr;
int main(int argc, char* argv[])
{
CPeople * p = &singleMgr::Instance();
if (NULL == p)
return 0;
p->SetAge(11);
printf("age: %d !\n",p->GetAge());
return 0;
}
没有考虑多线程安全情况,请各位大侠指教!@_~
本文介绍了一种使用模板元编程实现C++单例模式的方法,并提供了一个简单的示例程序。该实现允许任何类型创建其单例实例,但未考虑多线程安全问题。
3393

被折叠的 条评论
为什么被折叠?



