仅初始化结构或数组的前 n 个成员

Initialise first n members only of struct or array

我正在使用 RAD studio 10.2 附带的 clang 编译器(我认为是 c++ 11)。我今天错误地发现可以使用通常的大括号分配结构或数组的前 n 个成员,例如

int a[500]={1};
struct {int a,b,c;} st={2,3};

上面的编译和工作正常,但我从来没有遇到过这个或以前见过它,我在网上找不到它的提及(也许我正在使用错误类型的措辞进行搜索)。这个 c++ 有文档吗?

I've never come across this or seen it used before and I can find no mention of it online (maybe I'm searching using the wrong type of wording). Is this c++ documented?

是的,这已记录在案。这种语法称为列表初始化 - 更具体地说,因为类型是聚合:这是聚合初始化。

Initialise first n members only of struct or array

不可能只初始化一些成员/元素。如果你列出 initialise class 对象或数组,那么所有的都将被初始化。缺少初始化器的成员/元素将被初始化。

如果你想这样做,那么你可以做的是默认初始化 class 对象或数组,然后有选择地初始化子对象。

对于aggregate initialization,

(强调我的)

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 member 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).

这意味着,对于int a[500]={1};,第一个元素被初始化为1,数组中剩余的499个元素被值初始化为0。对于struct {int a,b,c;} st={2,3};,成员a被初始化为2b被初始化为3,最后一个成员c被值初始化为0 也是。