This is a static variable definition question for the parent class!

Asked 2 years ago, Updated 2 years ago, 22 views

template <typename T>
class Singleton
{
protected:
    Singleton() {}
    Singleton(const Singleton& single) {}
    ~Singleton() {}

protected:
    static T*   m_pInst;

public:
    static T* GetInst()
    {
        if (!m_pInst)
            m_pInst = new T;
        return m_pInst;
    }
    static void DesInst()
    {
        if (m_pInst)
            delete m_pInst;
        m_pInst = NULL;
    }
};

template <typename T>
T* Singleton<T>::m_pInst = NULL;

I thought there would be several static variables depending on the declared data type T if it was used as a template There is an error trying to define static variables in the child class.

template <typename T>
T* Singleton<T>::m_pInst = NULL;

There was no error when I wrote it like this, is it the right method? I wonder how that is allowed

c++

2022-09-21 19:15

1 Answers

Once a parent class's static member variable is not allowed to be defined by the child's name.

Creating a static member variable of a generic class in the header as shown below and including the header from multiple cpp files causes the redundant definition problem.

class Normal {
public:
    static int* number;
};
int Normal::number = 10;

This is because the code intNormal::number=10; is pasted into multiple cpp files during the include process and compiled to have number in multiple places.

However, in the case of templates, the story is different. As you know, the template is defined in the header. When you define a static member variable in a class template, you will be in a deadlock of whether this variable should be defined in the cpp file or in the header because it is a template. because it is a template?

In this case, allow the static member variable in the class template to be defined in the header as an exception. In this case, the compiler manages the variable to be created only once.

A similar variable template has been added since C++14.


2022-09-21 19:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.