Home > database >  Is this a list initialization or a value initialization?
Is this a list initialization or a value initialization?

Time:11-05

int i {};

Is this List Initialization or Value Initialization?

I can't distinguish them because I can't understand this sentence: a possibly empty brace-enclosed list of expressions or nested braced-init-lists from the link: https://en.cppreference.com/w/cpp/language/list_initialization

CodePudding user response:

Is this List Initialization or Value Initialization?

It is direct-list-initialization

T object { arg1, arg2, ... }; (1)

direct-list-initialization (both explicit and non-explicit constructors are considered)

  1. initialization of a named variable with a braced-init-list (that is, a possibly empty brace-enclosed list of expressions or nested braced-init-lists)

and the effect on T is value-initialization

Explanation

The effects of list initialization of an object of type T are:

[...]

  • Otherwise, if the braced-init-list has no elements, T is value-initialized.

And now for the value-initialization of integer you get zero-initialized.

Explanation

Value initialization is performed in these situations:

[...]

  1. otherwise, the object is zero-initialized.

CodePudding user response:

Whether it is a List or Value initialization depends on the object you are initializing. See https://en.cppreference.com/w/cpp/language/value_initialization:

If T is a class type that has no default constructor but has a constructor taking std::initializer_list, list-initialization is performed.

So since the object in this case in int which does not have a constructor taking a std::initializer_list and int is not an aggregate type, this is value initialization.

  • Related