Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:

  1. 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
  2. Pointers are being initialized to NULL by standard, why I need to explicitly initialize?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
441 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...