是sizeof(int())一个合法的表达式吗? [英] Is sizeof(int()) a legal expression?

查看:631
本文介绍了是sizeof(int())一个合法的表达式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题的灵感来自 sizeof(void())是法定表达式吗?

The expression in question is:

code> sizeof(int())

sizeof( int() )



在C ++语法中会出现:

In the C++ grammar there appears:


unary-expression:

unary-expression:


  • sizeof unary-expression

  • c> type-id

  • sizeof unary-expression
  • sizeof ( type-id )

但是,(int())可以匹配这两种情况下不同的含义:

however, ( int() ) can match both of these cases with different meanings:


  • 作为 unary-expression ,它是一个值初始化的 int prvalue, li>
  • 作为 type-id ,它是没有参数返回 int 的函数的类型。 li>
  • As a unary-expression, it is a value-initialized int prvalue, surrounded in redundant parentheses
  • As a type-id, it is the type of a function with no parameters returning int.

sizeof 的语义约束中,即C ++ 14 [expr.sizeof ] / 1,它解释说, sizeof( type-id

In the semantic constraints for sizeof, i.e. C++14 [expr.sizeof]/1, it explains that the form sizeof( type-id ) may not be applied to a function type.

但是我不确定是否违反该语义约束意味着 sizeof(int())是正确的,并使用 sizeof unary-expression 或者在语法匹配的早期阶段是否存在消除两种情况的其他规则。

However I'm not sure whether the violation of that semantic constraint implies that sizeof( int() ) is correct and uses the sizeof unary-expression form; or whether there is some other rule that disambiguates the two cases at an earlier stage of grammar matching.

注意。对于另一个问题 sizeof(void()),这两个解释都是无效的,所以可以认为编译器是正确的拒绝表达式, type-id 表单。但是,gcc拒绝 sizeof(int())和有关 type-id 的消息。

NB. For the other question sizeof(void()), neither interpretation is valid, so it could be argued that the compiler is correct to reject the expression with an error message indicating it matched the type-id form. However, gcc rejects sizeof( int() ) with a message about type-id.

要清楚,我的问题是: sizeof(int())一个法律表达式?,特别是关于语法匹配如何工作的细节

To be clear, my question is: "Is sizeof( int() ) a legal expression?", particularly on the detail of how the grammar matching works when both of the above bulleted cases match.

推荐答案

否, sizeof(int())是错误的,因为 int()被视为一个 type-id 。具体来说,它是一个函数类型, sizeof 不能应用于函数类型。

No, sizeof( int() ) is ill-formed because int() is taken to be a type-id. Specifically, it's a function type, and sizeof cannot be applied to a function type.

[dcl.ambig.res]/2

一个模糊性可能来自函数式
cast和一个 type-id 之间的相似性。该解决方案是任何可能
在其语法上下文中可能是 type-id 的构造应被认为是
type-id p>

An ambiguity can arise from the similarity between a function-style cast and a type-id. The resolution is that any construct that could possibly be a type-id in its syntactic context shall be considered a type-id.

此示例给出:


void foo(signed char a) {
    sizeof(int());                // type-id (ill-formed)
    sizeof(int(a));               // expression
    sizeof(int(unsigned(a)));     // type-id (ill-formed)


这篇关于是sizeof(int())一个合法的表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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