为什么是new int(*)[3]错误? [英] Why is new int (*)[3] an error?

查看:198
本文介绍了为什么是new int(*)[3]错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typedef int (*A)[3];

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

来自GCC的错误是错误:expected primary-expression before ')'token

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

推荐答案

标准定义了 new-type-id 作为新声明符的最长序列。还有一个注释,说明类似的情况(虽然它分配函数的指针):

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):


expr.new]

5.3.4 New [expr.new]

....

new-type-id : / em>

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

new-declarator:

     > ptr-operator new-declarator opt

     / em>

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

noptr-new-declarator:

     [  em>表达式 ]
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-seq opt

....

新表达式中的 new-type-id 新声明符
[注意:这可以防止声明符运算符& && * []
。 -  

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 ]

/ em>的新表达式可以
具有惊人的效果。 [示例

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

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

是错误的,因为绑定是

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

相反, new operator
可用于创建复合类型的对象(3.9.2):

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

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

为函数分配一个10个指针的数组(不带参数,
返回 int 。 -   end example ] -  结束注释]

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

这篇关于为什么是new int(*)[3]错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆