cplusplus / CWG

Core Working Group
23 stars 7 forks source link

P2434 [expr.reinterpret.cast] Is it implementable to produce the original value when `reinterpret_cast`-ing back from an integer? #543

Closed frederick-vs-ja closed 1 month ago

frederick-vs-ja commented 1 month ago

Full name of submitter (unless configured in github; will be published with the issue): Jiang An

Reference (section label): [expr.reinterpret.cast]

Link to reflector thread (if any):

Issue description:

[expr.reinterpret.cast] p5 specifies

[...] A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value ([basic.compound]); [...]

Consider this example:

union Foo {
  struct Bar {
    int p;
    int q;
  } x;

  struct Baz {
    int a[1];
  } y;
} u;

On common implemenations, reinterpret_cast from &u.x.p and &u.y.a[0] to an integer type produces the same value because two pointed-to objects have the same address. It is questionable whether the "will have its original value" part can be correctly implemented, because these two pointer values, despite being of the same type and representing the address of the same byte, are inequivalent and have different reachable bytes.

It's also problematic to reproduce the original pointer value that is invalid in the context of the cast. It seems that the current rule requires preserving the provenance and the related object structure of the source pointer in the resulted integer value, which is arguably impossible for most implementations.

Suggested resolution:

jensmaurer commented 1 month ago

While the C++ object model is fairly comprehensive, the question about pointer values obtained from round-tripping through integers remains open. The provenance proposal(s) for C have answers for these cases.

My understanding is that we want to allow the resulting pointer to point to the set of all valid options, similar to implicit object creation. Whether that's actually what everybody else wants, and whether there are any pitfalls, remains to be investigated.

This is not core issue material, but a research project; please submit a paper to EWG.

t3nsor commented 1 month ago

This is the subject of P2434

frederick-vs-ja commented 1 month ago

This is the subject of P2434

Thanks! I think this issue should be closed.