这是我的源代码。
#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不构造?为什么?因为这与模板一起使用?当我删除模板时,没关系;但现在,我无法得到消息。
答案 0 :(得分:1)
所以OP的问题是,为什么gc
没有在模板案例中实例化,因为如果它不是模板,它会被实例化为OP期望。 Point of Instantiation of Static Data Members和此问题的答案中C++ Static member initalization (template fun inside)解释了原因。
长话短说,您需要在代码中use
或reference
gc
进行实例化。例如,
static T* GetInstance()
{
gc;
return m_Instance;
}
将打印出预期的结果。