CWG2901 [basic.lval] Accessing an object through a different type through which it is type-accessible has undefined semantics (original) (raw)
Reference (section label): [basic.lval]
Issue description
int x = -1; auto y = *reinterpret_cast<unsigned*>(&x); // read value through different type *reinterpret_cast<unsigned*>(&x) = UINT_MAX; // modify value through different type
An object of type int is type-accessible through a glvalue of type unsigned.
However, [conv.lval] p3.4 states:
Otherwise, the object indicated by the glvalue is read ([defns.access]), and the value contained in the object is the prvalue result.
We obviously require a prvalue of unsigned type for the initialization of y, and the -1 value contained in the int object has the wrong type and and cannot be represented as unsigned.
Similarly, [expr.ass] p2 states:
In simple assignment (
=), the object referred to by the left operand is modified ([defns.access]) by replacing its value with the result of the right operand.
This cannot be done because it would require storing a UINT_MAX value of unsigned type in an object of type int.
Suggested resolution
In [basic.lval] p11, add the following sentence:
When an object of dynamic type
Tobjis accessed through a glvalue of typeTref,Tobjis type-accessible throughTref, andTrefis not the same type asTobj, an unspecified conversion from the stored value toTreftakes place when the object's value is read, and an unspecified conversion from the to-be-stored value toTobjtakes place when the object is modified.