初始化指向 nullptr
的动态指针数组的 C++ 是否有效?
int x = 10;
int** p = new int*[ x ]{ };
最佳答案
是的,代码是有效的,值初始化数组的每个元素。
有关标准引用,请参阅§5.3.4/17 [expr.new]
A new-expression that creates an object of type T initializes that object as follows:
—...
— Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.
然后是§8.5/7 [dcl.init]
To value-initialize an object of type T means:
—...
— if T is an array type, then each element is value-initialized;
— otherwise, the object is zero-initialized.
在这种情况下,最后一个项目符号适用于每个数组元素。
关于c++ - C++11 初始化列表可以与动态数组一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25394665/