c++ template singleton static pointer initialization in header file
c++, singleton, static-members, templates
Solution
You can fix your error by adding a definition for the `m_instance` member after the class definition.
template<typename T>
T* Singleton<T>::m_instance = nullptr;
For class templates, it's OK to add the definition of `static` members within the header itself, and won't lead to ODR violations.
But, as others have suggested, it's best to change you `getInstance()` definition to
static T& getInstance()
{
static T instance;
return instance;
}
C++11 even guarantees that the creation of the function local `static` variable `instance` will be thread-safe.
Problem
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?