在堆上初始化数组而不指定其长度

Initialize array on the heap without specifying its length

我正在阅读 Bjarne Stroustrup 的 Programming Principles and Practice Using C++(第二版)。第 597 页:

double* p5 = new double[] {0,1,2,3,4};

...; the number of elements can be left out when a set of elements is provided.

我将上面的代码输入 Visual Studio 2022,然后出现红色下划线,表示“不允许使用不完整的类型”(当我将 p5 定义为数据成员时会发生同样的事情),尽管如此,代码编译并成功运行

请问这样定义数组可以吗?如果是这样,为什么 Visual Studio 会显示那些红色下划线...?

May I ask if it is fine to define array in such way?

是的,从C++11开始是有效的。来自 new expression's documentation:

double* p = new double[]{1,2,3}; // creates an array of type double[3]

这意味着在你的例子中:

double* p5 = new double[] {0,1,2,3,4};

创建类型为 double[5] 的数组。

Demo


备注

这是在 p1009r2 中提出的。

如果它必须在堆上然后使用

std::vector<double> v{0, 1, 2, 3, 4};

如果可以入栈则使用

std::array a{0., 1., 2., 3., 4.}; // all elements must have the right type
std::array b(std::to_array<double>({1, 2, 3})); // when conversion is easier than typing fully typed objects