c++ - 为什么 new int (*)[3] 是错误的?

标签 c++ syntax-error new-operator

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 的错误是 error: expected primary-expression before ')' token 。为什么这个表达式中需要额外的括号?

最佳答案

标准将 new-type-id 定义为最长的 new-declarators 序列。还有一个注释,它说明了类似的情况(尽管它分配了指向函数的指针):

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 ]

关于c++ - 为什么 new int (*)[3] 是错误的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26029277/

相关文章:

c++ - 混合符号整数数学取决于变量大小

c++ - boost async_wait 并在绑定(bind)中添加 "this"

init.php 上的 PHP 错误消息

python - 在valueError循环中中断导致错误

c++ - "placement new"有什么用?

c++ - 如何在 Windows 中验证用户名和密码?

ruby-on-rails - PostgreSQL语法错误Rails 4

open-source - 加入开源列车

c++ - 删除具有堆成员的对象

c++ - #import 等效命令行