Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

c++ - Why is new int (*)[3] an error?

typedef int (*A)[3];

int (**p)[3] = new A;              // OK
int (**q)[3] = new (int(*)[3]);    // OK
int (**r)[3] = new int (*)[3];     // error

The error from GCC is error: expected primary-expression before ')' token . Why are the extra parentheses required in this expression?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The standard defines new-type-id as the longest sequence of new-declarators. There is also a note, which illustrates a similar situation (although it allocates pointers to functions):

5.3.4 New [expr.new]

....

new-type-id:
    type-specifier-seq new-declaratoropt

new-declarator:
    ptr-operator new-declaratoropt
    noptr-new-declarator

noptr-new-declarator:
    [ expression ]  attribute-specifier-seqopt
    noptr-new-declarator  [ constant-expression ]  attribute-specifier-seq opt

....

The new-type-id in a new-expression is the longest possible sequence of new-declarators. [ Note: this prevents ambiguities between the declarator operators &, &&, *, and [] and their expression counterparts. — end note ] [ Example:

new int * i; // syntax error: parsed as (new int*) i, not as (new int)*i

The * is the pointer declarator and not the multiplication operator. — end example ]

[ Note: parentheses in a new-type-id of a new-expression can have surprising effects. [ Example:

new int(*[10])(); // error

is ill-formed because the binding is

(new int) (*[10])(); // error

Instead, the explicitly parenthesized version of the new operator can be used to create objects of compound types (3.9.2):

new (int (*[10])());

allocates an array of 10 pointers to functions (taking no argument and returning int. — end example ] — end note ]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...