c++ template singleton static pointer initialization in header file

后端 未结 5 1226
有刺的猬
有刺的猬 2020-12-07 03:13

What is wrong with this implementation in header file?

template 
class Singleton
{
public:
    static T* getInstance() 
    {
        if (m         


        
5条回答
  •  天命终不由人
    2020-12-07 04:14

    You can fix your error by adding a definition for the m_instance member after the class definition.

    template
    T* Singleton::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.

提交回复
热议问题