What is wrong with this implementation in header file?
template <typename T>
class Singleton
{
public:
static T* getInstance()
{
if (m_instance == NULL)
{
m_instance = new T();
}
return m_instance;
}
private:
static T* m_instance;
};
I use it like this:
typedef Singleton<MyClass> MyClassSingleton;
I get linker error:
error LNK2001: unresolved external symbol "private: static class MyClass * Singleton<class MyClass>::m_instance" (?m_instance@?$Singleton@VMyClass@@@@0PAVMyClass@@A)
When I add
template <typename T> T* Singleton<T>::m_instance = NULL;
it works, but I worry on two things:
- Static member should be defined in .cpp file in order to have only one instance in all compilation units, even if you include the header file into 10 source files
- Pointers are being initialized to NULL by standard, why I need to explicitly initialize?