Skip to content

CWG2901 [basic.lval] Accessing an object through a different type through which it is type-accessible has undefined semantics #548

Closed
cplusplus/draft
#7458
@Eisenwave

Description

@Eisenwave

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 Tobj is accessed through a glvalue of type Tref, Tobj is type-accessible through Tref, and Tref is not the same type as Tobj, an unspecified conversion from the stored value to Tref takes place when the object's value is read, and an unspecified conversion from the to-be-stored value to Tobj takes place when the object is modified.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions