gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:36:55 26 4
gpt4 key购买 nike

我正在尝试使用初始值设定项列表初始化动态声明的数组,但我注意到我必须使用 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 : new 表达式中的数组大小推导,已为 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 expressioninside the square brackets is currently mandatory according to the C++ grammar. When uniforminitialization was introduced for C++11, the rule about deducing the size of the array from thenumber of initializers was never extended to the new-expression case. Presumably this was simplyoverlooked. 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 effectof the wording changes should be applied in implementations of all previous versions of C++ wherethey apply. [...]


来自 GCC's C++ Standards Support pages我们可能会注意到 GCC 列出了从 GCC 11 开始实现的 P1009R2,并且我们可以验证 GCC 11 已经向后移植了实现以接受 OP 的示例,就像 C++11 一样格式良好。
DEMO (海湾合作委员会 11/ -std=c++11)。

关于c++ - 使用初始化列表声明动态分配数组的数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66780643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com