Does initialization entail lvalue-to-rvalue conversion? Is `int x = x;` UB?

前端 未结 4 596
天涯浪人
天涯浪人 2020-11-22 07:50

The C++ standard contains a semi-famous example of \"surprising\" name lookup in 3.3.2, \"Point of declaration\":

int x = x;

This initializ

4条回答
  •  悲哀的现实
    2020-11-22 08:07

    An implicit conversion sequence of an expression e to type T is defined as being equivalent to the following declaration, using t as the result of the conversion (modulo value category, which will be defined depending on T), 4p3 and 4p6

    T t = e;
    

    The effect of any implicit conversion is the same as performing the corresponding declaration and initialization and then using the temporary variable as the result of the conversion.

    In clause 4, the conversion of an expression to a type always yields expressions with a specific property. For example, conversion of 0 to int* yields a null pointer value, and not just one arbitrary pointer value. The value category too is a specific property of an expression and its result is defined as follows

    The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type (8.3.2), an xvalue if T is an rvalue reference to object type, and a prvalue otherwise.

    Hence we know that in int t = e;, the result of the conversion sequence is a prvalue, because int is a non-reference type. So if we provide a glvalue, we are in obvious need of a conversion. 3.10p2 further clarifies that to leave no doubt

    Whenever a glvalue appears in a context where a prvalue is expected, the glvalue is converted to a prvalue; see 4.1, 4.2, and 4.3.

提交回复
热议问题