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

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

c++ template singleton static pointer initialization in header file

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...