Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you omit the array size in a new initializer?

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
like image 537
user4375981 Avatar asked Dec 18 '14 22:12

user4375981


1 Answers

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?"

Regarding 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.

Regarding 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.

like image 116
cdhowie Avatar answered Oct 08 '22 03:10

cdhowie