C++ primer 动态数组的初始值设定项数量超出大小

C++ primer dynamic array number of initializers exceeds the size

在 C++ primer 5 版中。第 12 章动态内存:

If there are fewer initializers than elements, the remaining elements are value initialized. If there are more initializers than the given size, then the new expression fails and no storage is allocated. In this case, new throws an exception of type bad_array_new_length. Like bad_alloc, this type is defined in the new header.

这是关于分配和初始化动态数组的。但我认为这是不正确的:如果初始化器的数量大于动态数组的大小,那么这是一个编译时错误而不是运行时错误:

auto p = new int[3]{4, 5, 6, 7}; // compile-time error: Too many initializers.

这可能是一个编译时错误,如果您使用常量作为数组大小并且编译器可以清楚地告诉您存在问题。

但是,在很多情况下,分配的内存大小不是常量,而是一个无法在编译时推导出来的变量。在这种情况下,将在 运行 时间抛出异常。