C++ Logo


Advanced search

Re: P1839 and the object representation of subobjects

From: Thiago Macieira <thiago_at_[hidden]>
Date: Tue, 21 Jul 2020 16:29:48 -0700
On Tuesday, 21 July 2020 12:44:13 PDT language.lawyer--- via Std-Proposals
> auto qoptr2 = reinterpret_cast<QObject *>(
> reinterpret_cast<byte *>(c1ptr) - off
> );
> assert(qoptr == qoptr2);
> if `c1ptr` really points to member subobject, `reinterpret_cast<byte
> *>(c1ptr)` points to the **first** element of its object representation, so
> subtracting a positive number from such a pointer value is UB because of
> [expr.add]/4.

IIUC, what you're saying is that, given:

struct S
    int i, j;

You can take a pointer to S and get to its underlying representation as an
array of bytes, so you can do arithmetic plus std::launder and get to the
member j.

expr.add/4 says about negative offsetting:

 [...] the expression P - J points to the (possibly-hypothetical)
 array element i−j of x if 0≤i−j≤n.
 Otherwise, the behavior is undefined.

IIUC, you're saying that casting the int pointer to a byte representation
returns the first (index 0) element of the representation, so subtracting a
positive number results in a negative index, which means UB.

Why can't it be understood to return the 5th element of S's representation?

Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DPG Cloud Engineering

Received on 2020-07-21 18:33:09