简体   繁体   中英

Is this aggregate initialization or default initialization in C++?

Consider following program.

#include <iostream>
int main()
{
    int a=int{};
    std::cout<<a;
}

Is it uses aggregate initialization or default initialization? I am confused.

Empty parentheses or braces ( T() or T{} ) perform value initialization . The exception would be the case where the type is an aggregate in which case aggregate initialization would be used. Since int is not an aggregate, it will be value initialized and since it's not a class nor an array, value initialization will do zero-initialization.

You were wondering why it doesn't work in C. Such syntax simply doesn't exist in C, see this answer .

Aggregate initialization is a type of list initialization, which initializes aggregates . An aggregate is an object of type array, or object which has the characteristics defined on this page.

In this case, the type of initialization is most likely value initialization.

Since C++11, by comparison with other SO answers (eg: this or this ), I would say this is:

  1. a value-initialization ( int{} ) followed by
  2. a copy-initialization ( int a=int{} ).

By the way, from C++17 , the second step should vanish as int{} is required to directly initialize a .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM