为什么在什么都不初始化时使用初始化列表?

Why use an initializer list when it initializes nothing?

在此代码段中:

struct Result
{
    Result() : output1(){};
    int output1[100];
}

Result() : output1(){}; 是做什么的?

我知道 : output1() 是初始化列表,但为什么在它什么都不做的时候还要提到它?

它做了一些事情:它对 output1 进行了零初始化,而不是让它保持未初始化状态。

详细来说,这叫做值初始化,这里有详细解释:https://en.cppreference.com/w/cpp/language/value_initialization

The effects of value initialization are:

  1. if T is a class type with no default constructor or with a user-provided or deleted default constructor, the object is default-initialized;
  2. if T is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;
  3. if T is an array type, each element of the array is value-initialized;
  4. otherwise, the object is zero-initialized.

因为是数组,适用情况3。然后规则递归地应用于数组中的每个值,导致将值设置为 0 的情况 4。