c++ template singleton static pointer initialization in header file

后端 未结 5 1210
有刺的猬
有刺的猬 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 03:58

    If you're really want to use a singleton, and you're really sure you want to use a templated singleton, you may want to use Scott Meyer's singleton approach:

    template <typename T>
    class Singleton
    {
    public:
       static Singleton<T>& getInstance() {
           static Singleton<T> theInstance; 
           return theInstance;
       }
    
    private:
       Singleton() {}
       Singleton(const Singleton<T>&);
       Singleton<T>& operator=(const Singleton<T>&);
    };
    
    0 讨论(0)
  • 2020-12-07 04:00

    Static members always need to be initialized exactly once, including those from template instantiations.

    You can avoid this with local statics if you really like:

    template <typename T>
    T *Singleton<T>::getInstance() {
      // Will be lazy initialized on first call (instead of startup) probably.
      static T instance;
      return &instance;
    }
    

    Or:

    // No need to use pointers, really...
    template <typename T>
    T &Singleton<T>::getInstance() {
      static T instance;
      return instance
    };
    
    0 讨论(0)
  • 2020-12-07 04:00

    Others have answered how to fix the code, but your question was also about the reasoning. By way of explanation, what you are struggling with is the difference between declaration and definition. In this line:

    static T* m_instance;
    

    You are declaring that there is a name for m_instance, but you have not defined the space. The line of code you added defines the space.

    0 讨论(0)
  • 2020-12-07 04:02

    Pointers are being initialized to NULL by standard, why I need to explicitly initialize?

    You don't need.

    template <typename T>
    T* Singleton<T>::m_instance;
    

    This will suffice as static & global variables are zero initialized by default

    Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place.

    0 讨论(0)
  • 2020-12-07 04:14

    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.

    0 讨论(0)
提交回复
热议问题