为什么不能在新的初始化程序中忽略数组大小? [英] Why can't you omit the array size in a new initializer?
问题描述
这是允许的:
int a[]{1, 2, 3};
但不是这样:
auto a = new int[]{1, 2, 3};
您必须指定范围.为什么?
You have to specify the bounds. Why?
正确的语法(不能编译)是:
The proper syntax (that doesn't compile) is:
auto a = new (int[]){1, 2, 3};
这给出了真实的错误消息,即:
This gives the real error message, which is:
error: invalid use of array with unspecified bounds
推荐答案
MSalters的答案解决了为何没有这样做的原因在最新版本的标准中进行了更改.在这里,我将回答伴随的问题:在C ++ 11标准中哪里禁止这样做?"
MSalters' answer addresses why this hasn't been changed in recent versions of the standard. Here I will answer the companion question, "where in the C++11 standard is this forbidden?"
首先,我们需要注意 int []
是不完整的类型.
First, we need to note that int[]
is an incomplete type.
...未知大小的数组...是未完全定义的对象类型.-[basic.types]§3.9¶5
... an array of unknown size ... is an incompletely-defined object type. -[basic.types] §3.9 ¶5
最后,我们注意到 new
运算符不允许指定的类型不完整:
Finally, we note that the new
operator does not permit the specified type to be incomplete:
此类型应为完整的对象类型...-[expr.new]§5.3.4¶1
This type shall be a complete object type ... -[expr.new] §5.3.4 ¶1
在使用 braced-init-list 语法的情况下,标准中没有任何例外.
There isn't anything in the standard to make an exception for this case when the braced-init-list syntax is used.
int []
使用 new-type-id 生产进行解析,该生产使用 noptr-new-declarator 生产解析方括号:
int[]
in this case gets parsed using the new-type-id production, which uses the noptr-new-declarator production to parse the square brackets:
noptr-new-declarator:
[ expression ] attribute-specifier-seq opt
noptr-new-declarator [ constant-expression ] attribute-specifier-seq opt
noptr-new-declarator:
[ expression ] attribute-specifier-seqopt
noptr-new-declarator [ constant-expression ] attribute-specifier-seqopt
请注意,表达式没有标记为可选,因此该语法无法解析.
Note that expression is not marked optional, therefore this syntax simply fails to parse.
这篇关于为什么不能在新的初始化程序中忽略数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!