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

前端 未结 3 1952
执念已碎
执念已碎 2021-01-04 01:01

This is allowed:

int a[]{1, 2, 3};

But not this:

auto a = new int[]{1, 2, 3};

You have to specify the bou

3条回答
  •  时光取名叫无心
    2021-01-04 01:38

    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.

提交回复
热议问题