简体   繁体   English

这是C ++中的聚合初始化还是默认初始化?

[英]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 . 空括号或大括号( T()T{} )执行值初始化 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. 由于int不是集合,因此将对其进行值初始化,并且由于它不是类也不是数组,因此值初始化将进行零初始化。

You were wondering why it doesn't work in C. Such syntax simply doesn't exist in C, see this answer . 您想知道为什么它在C中不起作用。这种语法在C中根本不存在,请参见此答案

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: 从C ++ 11开始,通过与其他SO答案(例如thisthis )进行比较,我会说这是:

  1. a value-initialization ( int{} ) followed by 值初始化int{} )后跟
  2. a copy-initialization ( int a=int{} ). 复制初始化int a=int{} )。

By the way, from C++17 , the second step should vanish as int{} is required to directly initialize a . 顺便说一下,从C ++ 17开始 ,第二步应该消失了,因为需要int{}直接初始化a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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