使用表达式列表在 C++ 20 中初始化多维数组

Initializing a multi-dimensional array in C++ 20 using an expression list

在 C++ 20 中使用表达式列表初始化多维数组是否正确?

int a[][3]( 1, 2, 3, { 4, 5, 6 } );

至少MS VS 2019的C++编译器不会编译这样的声明

这个声明

int a[][3]( 1, 2, 3, 4, 5, 6 );

在此声明时也未编译

int a[][3]( { 1, 2, 3 }, { 4, 5, 6 } );

编译成功

在 C++ 20 标准(9.4 初始化程序)中与数组初始化相关的相应引述中,没有说明使用表达式列表时是否允许大括号省略。

(17.5) — Otherwise, if the destination type is an array, the object is initialized as follows. Let x1, . . . , xk be the elements of the expression-list. If the destination type is an array of unknown bound, it is defined as having k elements. Let n denote the array size after this potential adjustment. If k is greater than n, the program is ill-formed. Otherwise, the ith array element is copy-initialized with xi for each 1 ≤ i ≤ k, and value-initialized for each k < i ≤ n. For each 1 ≤ i < j ≤ n, every value computation and side effect associated with the initialization of the ith element of the array is sequenced before those associated with the initialization of the jth element.

取自c++ 20 draft

7.6.1
expression-list:
  initializer-list

9.4
initializer-clause :
   assignment-expression
   braced-init-list

initializer-list:
   initializer-clause ...opt
   initializer-list , initializer-clause ...opt

a[][2]({1, 2, 3}, {4, 5, 6}) 可以

a[][2](1, 2, 3, {4, 5, 6}) 不行,因为 1, 2, 3, {4, 5, 6} 不是表达式列表

这意味着数组的 () 语法毫无意义,无论如何内部部分需要是 {} 除了:

int e[](1);

因为 1 是一个赋值表达式

重新阅读提供的报价,尤其是这部分

the ith array element is copy-initialized with xi for each 1 ≤ i ≤ k

好像是这样初始化的

int a[][3]( 1, 2, 3, { 4, 5, 6 } );

确实不正确,因为数组 a 的元素又是类型 int[3] 的数组,在这种情况下要初始化它,您需要使用花括号初始化列表。之后在 braced-init-list 中,大括号省略将被接受。那就是你不能用表达式初始化数组。

这里有一个例子可以证实,并且是由MS VS 2019的C++编译器编译的

int e[][2][3]( { 1, 2, 3,  { 4, 5, 6 } }, { 6, 5, 4, 3, 2, 1 } );

在大括号初始化列表中,可以使用大括号省略。