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

6

我试图使用初始化列表初始化一个动态声明的数组,但我注意到在使用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.

Clang也接受两个版本演示 - Jarod42
initializer-list 标签是指 std::initializer_list - 463035818_is_not_a_number
虽然我不能百分之百确定并详细说明,但我认为g++在这里是错误的,第二个版本应该被接受。这个参考链接也给出了double* p = new double[]{1,2,3};作为可行的例子。 - Lukas-T
https://github.com/cplusplus/draft/commit/44d91596bf91ddbaada724ceda4d893a853dd444 - Language Lawyer
1个回答

3
这是C++20中实现的新表达式中的数组大小推导,请参阅P1009R2。

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的C++标准支持页面可以看出,GCC将P1009R2列为在GCC 11中已实现,并且我们可以验证GCC 11已将实现向后移植,以接受OP的示例作为符合C++11的规范。

演示(GCC 11 / -std=c++11)。


感谢您的回复。我想我的问题是,如果GCC已经实现了这个功能,为什么它对我不起作用呢? - Mohammad Ali
1
@MohammadAli 请看我的回答的最后一部分:这已经在GCC 11中实现了;任何此之前的版本(比如,GCC 10)都不包含此功能。由于GCC 11是尖端技术,你可能在自己的工具链中使用了旧版本。 - dfrib
谢谢,我误以为需要使用C++11标准或更高版本。 - Mohammad Ali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接