使用初始化列表声明动态分配数组的数组大小

Declaring array size for dynamically allocated array with initializer list

我正在尝试使用初始化程序列表来初始化动态声明的数组,但我注意到我必须使用 GCC 提供数组大小,否则会出现错误。如果忽略数组大小,使用 MSVC 尝试相同操作不会导致任何错误。使用带有动态数组的初始化列表时是否强制提供数组大小?这是实现定义的东西吗,这就是为什么两个编译器都不同的原因?

int *array { new int [3] {0, 1, 2} }; // Works with both MSVC and GCC.
int *array { new int [] {0, 1, 2} }; // Works only with MSVC, not GCC.

这是 P1009R2新表达式中的数组大小推导,它是为 C++20 实现的。

Bjarne Stroustrup pointed out the following inconsistency in the C++ language:

double a[]{1,2,3}; // this declaration is OK, ...
double* p = new double[]{1,2,3}; // ...but this one is ill-formed!

Jens Maurer provided the explanation why it doesn’t work: For a new-expression, the expression inside the square brackets is currently mandatory according to the C++ grammar. When uniform initialization was introduced for C++11, the rule about deducing the size of the array from the number of initializers was never extended to the new-expression case. Presumably this was simply overlooked. There is no fundamental reason why we cannot make this work [...]

Proposed wording

The reported issue is intended as a defect report with the proposed resolution as follows. The effect of the wording changes should be applied in implementations of all previous versions of C++ where they apply. [...]

GCC's C++ Standards Support pages 我们可能会注意到 GCC 列出了从 GCC 11 开始实施的 P1009R2,并且我们可能会验证 GCC 11 已经向后移植了实施以接受 OP 的例子,因为早在很久以前作为 C++11.

DEMO(海湾合作委员会 11/-std=c++11)。