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? 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. 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).
Long story short, you need to use
or reference
gc
in your code to instantiate. For example,
static T* GetInstance()
{
gc;
return m_Instance;
}
will print out the result expected.