Is temporary object originally const?

前端 未结 2 1727
谎友^
谎友^ 2020-12-29 11:46

Is this code UB?

struct A
{
 void nonconst() {}
};

const A& a = A{};
const_cast(a).nonconst();

In other words, is the (t

2条回答
  •  不思量自难忘°
    2020-12-29 12:09

    The initialization of the reference a is given by [dcl.init.ref]/5 (bold mine):

    Otherwise, if the initializer expression

    • is an rvalue (but not a bit-field)[...]

    then the value of the initializer expression in the first case and the result of the conversion in the second case is called the converted initializer. If the converted initializer is a prvalue, its type T4 is adjusted to type “cv1 T4” ([conv.qual]) and the temporary materialization conversion ([conv.rval]) is applied.

    So it means that the type prvalue expression that initialize the reference, A{}, is adjusted to const A.

    Then [conv.rval] states:

    A prvalue of type T can be converted to an xvalue of type T. This conversion initializes a temporary object ([class.temporary]) of type T.

    So the type of the temporary object, bound to the reference is the same as the adjusted prvalue type: const A.

    So the code const_cast(a).nonconst(); is undefined behavior.

提交回复
热议问题