Home > Net >  Why use an initializer list when it initializes nothing?
Why use an initializer list when it initializes nothing?

Time:11-29

In this snippet:

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

What does Result() : output1(){}; do?

I know that : output1() is the initializer list, but why even mention it when it does nothing?

CodePudding user response:

It does something: It zero-initializes output1 instead of leaving it uninitialized.

To elaborate, this is called value initialization and is explained in detail here: 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.

Since it is an array, case 3 applies. Then the rule applies recursively for each value in the array, leading to case 4 which sets the value to 0.

  • Related