[英]why the internal class is't constructed? C++
This is my source code. 这是我的源代码。
#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;
}
When I build the project, the internal class CGarbageCollection is not constructed? 当我构建项目时,内部类CGarbageCollection是否未构建? Why?
为什么? Because this is used with template?
因为这与模板一起使用? When I delete the template, It's ok;
当我删除模板时,就可以了; but now, I cannot get the message.
但现在,我无法收到消息。
So OP's question is, why gc
is not instantiated in the template case because if it is not a template it is instantiated as OP expects. 因此,OP的问题是,为什么在模板情况下不实例化
gc
,因为如果它不是模板,则会按照OP的期望进行实例化。 The reason is explained in Point of Instantiation of Static Data Members and in the answers of this question C++ Static member initalization (template fun inside) . 原因在“静态数据成员的实例化点”和此问题的答案C ++静态成员初始化(内部模板有趣)中得到了解释 。
Long story short, you need to use
or reference
gc
in your code to instantiate. 长话短说,您需要在代码中
use
或reference
gc
进行实例化。 For example, 例如,
static T* GetInstance()
{
gc;
return m_Instance;
}
will print out the result expected. 将打印出预期的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.