'How does casting between pointer-interconvertible objects work in cases of ambiguity?
The standard ([expr.static.cast#13]) says that:
A prvalue of type “pointer to cv1 void” can be converted to a prvalue of type “pointer to cv2 T”. [...] If the original pointer value points to an object a, and there is an object b of type T (ignoring cv-qualification) that is pointer-interconvertible with a, the result is a pointer to b. Otherwise, the pointer value is unchanged by the conversion.
To me, this sounds a bit like there should always be at most one such object b that is pointer-interconvertible with a. But consider the following example:
struct X { };
struct Y { X xx; };
union Z { X x; Y y; };
All of the above types are standard layout classes ([class.prop#3]). In the following code:
Z z = {};
the object z is pointer-interconvertible ([basic.compound#4]) with z.x, but also with z.y.xx (because z is pointer-interconvertible with z.y, and z.y is pointer-interconvertible with z.y.xx).
Therefore, my question is: which of the objects will the following pointer refer to? (I'm using reinterpret_cast because it's equivalent to static_casting to void* and then to X*)
X* ptr = reinterpret_cast<X*>(&z);
I am aware that in my example, z.y is not within its lifetime, but I assume that isn't a problem, because cppreference.com has a similar example where one of the objects is not within its lifetime:
[...]
union U { int a; double b; } u = {0};
[...]
int* p3 = reinterpret_cast<int*>(&u); // value of p3 is "pointer to u.a": u.a and u are
// pointer-interconvertible
double* p4 = reinterpret_cast<double*>(p3); // value of p4 is "pointer to u.b": u.a and
// u.b are pointer-interconvertible because
// both are pointer-interconvertible with u
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
