C 数组和结构中的 C++ 统一初始化

C++ uniform initialization in C arrays and structs

我看过一些类似这样的旧代码:char foo[100] = { 0 };。结构也会发生类似的情况,例如:STRUCT st = { 0 };。这两种情况的意图都很明确,即对各自的变量进行零初始化。因此,char foo[100] {};STRUCT st {}; 会更加地道。

我的问题是:带有 <variable> = { 0 } 的代码是否应该达到相同的结果?我已经用发布构建的二进制文件对此进行了测试,并且元素似乎是零初始化的,但这是否由标准保证?在我看来 <variable> = { 0 } 应该只保证变量的第一个元素(数组元素或结构成员)为零。

此外,类似的声明 char foo[100] = {};STRUCT st = {} 表示什么行为?

(这个问题背后的动机是我将所有声明更改为惯用形式,但如果不能保证零初始化,那么问题就更严重了,值得开票。)

It seems to me that <variable> = { 0 } should only guarantee for the first element of the variable (array element or struct member) to be zero.

对于 POD 类型,该语法与 <variable> = {};

相同

任何未明确指定的都初始化为零。只有当 some_value 不为零时,使用 <variable> = { somve_value } 才会有所不同。

即使相同的语法可用于 non-POD 类型,但未显式初始化的 non-POD 类型的元素将使用其默认构造函数进行初始化。

来自 8.5.1 Aggregates/7:

If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from an empty initializer list ([dcl.init.list]). [ Example:

struct S { int a; const char* b; int c; };
S ss = { 1, "asdf" };

initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is, 0. — end example ]