Search code examples
c++initialization

Does std::list variable in the class need initialization?


I have recently read something like this. I konw it is not so complex. But as a beginner, I just don't know why it works, so here is the description.

#include <list>
#include <iostream>

using namespace std;
 
template <typename T>
class A
{
public:
    list<T *> testlist;
    A();
    ~A();
    void m_append(T* one);
};

template <typename T>
A<T>::A()
{
    cout << "constructor" << endl;
}

template <typename T>
A<T>::~A()
{
    cout << "destructor" << endl;
}

template <typename T>
void A<T>::m_append(T* one)
{
    cout << *one << " push in" << endl;
    testlist.push_back(one);
}

int main(void)
{
    A<int> a;
    int b = 4;
    int c = 5;
    int d = 6;
    a.m_append(&b);
    a.m_append(&c);
    a.m_append(&d);

    return 0;
}

In my opinion this testlist is not initialized, there should be something wrong.

But it works.

constructor
4 push in
4
5 push in
5
6 push in
6
destructor

So I am pretty confused. There is no need to initialize this testlist or?


Solution

  • Data member testlist is not mentioned in the member initializer list of constructor of A, and doesn't have default member initializer (since C++11), then it would be default initialized via the default constructor of std::list.

    1. when a base class or a non-static data member is not mentioned in a constructor initializer list and that constructor is called.

    And

    There is no need to initialize this testlist or?

    It depends on your intent. If the default initialization is enough, then yes.