Does not evaluating the expression to which sizeof is applied make it legal to dereference a null or invalid pointer inside sizeof in C++?

后端 未结 3 521
迷失自我
迷失自我 2020-11-27 21:04

First of all, I\'ve seen this question about C99 and the accepted answer references operand is not evaluated wording in the C99 Standard draft. I\'m not sure this a

3条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 21:56

    Since you explicitly asked for standard references - [expr.sizeof]/1:

    The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id.

    [expr]/8:

    In some contexts, unevaluated operands appear (5.2.8, 5.3.3, 5.3.7, 7.1.6.2). An unevaluated operand is not evaluated.

    Because the expression (i.e. the dereferenciation) is never evaluated, this expression is not subject to some constraints that it would normally be violating. Solely the type is inspected. In fact, the standard uses null references itself in an example in [dcl.fct]/12:

    A trailing-return-type is most useful for a type that would be more complicated to specify before the declarator-id:

    template  auto add(T t, U u) -> decltype(t + u);
    

    rather than

    template  decltype((*(T*)0) + (*(U*)0)) add(T t, U u);
    

    — end note ]

提交回复
热议问题