This is allowed:
int a[]{1, 2, 3};
But not this:
auto a = new int[]{1, 2, 3};
You have to specify the bounds. Why?
EDIT: 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' 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?"
new (int[]){1, 2, 3}
First, we need to note that int[]
is an incomplete type.
... an array of unknown size ... is an incompletely-defined object type. -[basic.types] §3.9 ¶5
Finally, we note that the new
operator does not permit the specified type to be incomplete:
This type shall be a complete object type ... -[expr.new] §5.3.4 ¶1
There isn't anything in the standard to make an exception for this case when the braced-init-list syntax is used.
new int[]{1, 2, 3}
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-seqopt
noptr-new-declarator [ constant-expression ] attribute-specifier-seqopt
Note that expression is not marked optional, therefore this syntax simply fails to parse.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With