C++ 初始化零数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38892455/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:47:12  来源:igfitidea点击:

Initializing an array of zeroes

c++arraysinitializationlanguage-lawyer

提问by Yves Daoust

It is well known that missing initializers for an array of scalars are defaulted to zero.

众所周知,标量数组缺少的初始值设定项默认为零。

int A[5]; // Entries remain uninitialized
int B[5]= { 0 }; // All entries set to zero

But is this (below) guaranteed ?

但这(下面)有保证吗?

int C[5]= { }; // All entries set to zero

回答by Bathsheba

The empty braced initialisation performs aggregation-initialization of the array: this leads to zero-initialization of the intelements.

空括号初始化执行数组的聚合初始化:这导致int元素的零初始化。

Yes, this is guaranteed.

是的,这是有保证的。

回答by songyuanyao

Yes, according to the rule of aggregate initialization, it's guaranteed (that all elements of array Cwill be value-initialized, i.e. zero-initializedto 0in this case).

是,根据该规则集合初始化,它保证(即数组的所有元素C值初始化,即零初始化0在这种情况下)。

(emphasis mine)

(强调我的)

If the number of initializer clauses is less than the number of members and bases (since C++17)or initializer list is completely empty, the remaining members and bases (since C++17)are initialized by their default initializers, if provided in the class definition, and otherwise (since C++14)by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates).

如果初始化子句的数量少于成员的数量and bases (since C++17)初始化列表完全为空,则其余成员由空列表and bases (since C++17)初始化by their default initializers, if provided in the class definition, and otherwise (since C++14),按照通常的列表初始化规则(对非类类型执行值初始化和具有默认构造函数的非聚合类,以及聚合的聚合初始化)。



PS:

PS:

int A[5]; // Entries remain uninitialized

"remain uninitialized" might not be accurate. For int A[5];, all elements of Awill be default-initialized. If Ais static or thread-local object, the elements will be zero-initializedto 0, otherwise nothing is done, they'll be indeterminate values.

“保持未初始化”可能不准确。对于int A[5];, 的所有元素都A将被默认初始化。如果A是静态或线程本地对象,元素将被零初始化0,否则什么都不做,它们将是不确定的值。

回答by rain_

In fact when you sayint A[5] = { 0 };you are saying: Initialize the first element to zero. All the other positions are initialized to zero because of the aggregate inizialization.

事实上,当你说int A[5] = { 0 };你是在说:将第一个元素初始化为零。由于聚合初始化,所有其他位置都初始化为零。

This line is the real responsible for having your array full of zeroes: int A[5] = { };

这一行真正负责让你的数组充满零: int A[5] = { };

That is why if you use int A[5] = { 1 };you will only have the first position inizialized to 1.

这就是为什么如果您使用,int A[5] = { 1 };您只会将第一个位置初始化为 1。