【发布时间】:2014-08-14 15:58:16
【问题描述】:
这是我的源代码。
#include <iostream>
using namespace std;
class MySingleton;
template<class T>
class CSingleton
{
public:
CSingleton()
{
cout << "constructor" << endl;
}
static T* GetInstance()
{
return m_Instance;
}
private:
static T* m_Instance;
// This is important
class CGarbageCollection
{
public:
CGarbageCollection()
{
cout << "CGarbageCollection init\r\n";
}
~CGarbageCollection()
{
// We can destory all the resouce here, eg:db connector, file handle and so on
if (m_Instance != NULL)
{
cout << "Here is the test\r\n";
delete m_Instance;
m_Instance = NULL;
}
}
};
static CGarbageCollection gc;
};
template<class T>
typename CSingleton<T>::CGarbageCollection CSingleton<T>::gc;
template<class T>
T* CSingleton<T>::m_Instance = new T();
class MySingleton : public CSingleton<MySingleton>
{
public:
MySingleton(){}
~MySingleton(){}
};
int main()
{
MySingleton *pMySingleton = MySingleton::GetInstance();
return 0;
}
我构建项目的时候,内部类CGarbageCollection没有构建?为什么?因为这是与模板一起使用的?当我删除模板时,没关系;但现在,我无法收到消息。
【问题讨论】:
-
如果你坚持使用单例模式,should be considered harmful,你至少应该知道/使用Meyers singleton。
-
@NeilKirk:这不是线程安全的,应该避免。
-
@NeilKirk 更好的是,将
unique_ptr设为函数的static局部变量。使用 C++11 线程安全静态,您无需付出额外的努力即可获得线程安全。 -
@Angew:为什么需要免费分配商店?
-
@RobertAllanHenniganLeahy 当然你不知道。我只是在评论“静态
unique_ptr”部分。
标签: c++ templates static internal