class中的std::list变量是否需要初始化?

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

我最近读到这样的东西。我知道它并不那么复杂。但是作为一个初学者,我就是不知道为什么会这样,所以这里描述一下。

#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;
}

我认为这个testlist没有初始化,应该有问题。

但它有效。

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

所以我很困惑。不需要初始化这个 testlist 或者?

数据成员 testlist 未在 A 的构造函数的成员初始值设定项列表中提及,并且没有默认成员初始值设定项 (C++11 起),则它将是 default initialized 通过 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.

There is no need to initialize this testlist or?

这取决于你的意图。如果默认初始化就够了,那就是。

要理解这一点,您必须知道列表是如何构造的。 它在堆栈上有一个控制块,然后如果您插入元素,则在堆上分配元素。控制块由构造函数初始化。

这里有一张图片来理解它的样子:

所以你不需要初始化列表。