Let's say that I have a value:
int i = 0;
And an empty class eligible for being empty-base optimized:
struct Empty{
// stuff that passes
// static_assert( std::is_empty<Empty>::value );
};
Is it legal to:
Empty& e = *reinterpret_cast<Empty*>(reinterpret_cast<void*>(&i)); //?
// do stuff with e
According to this online C++ standard draft, a cast from one pointer type to a different pointer type and then back is conditionally valid:
This means, that the cast per se from
int*toEmpty*is valid as long asEmptydoes not have stricter alignment requirements thanint, and you can later cast back toint*.Note, however, that this does not mean that you may access/dereference the
Empty*-object (as it isn't anEmpty-object to which the pointer points).So the pure cast is OK, but dereferencing it then yields UB.