Question Details

No question body available.

Tags

c++

Answers (2)

February 16, 2026 Score: 3 Rep: 68,547 Quality: Medium Completeness: 80%

Two unrelated types can be layout compatible (as they are here) when they're standard layout and have a common initial sequence comprising all their members.

Type-punning layout compatible types via a union is explicitly permitted.

The equivalent type-punning via reinterpret_cast is not (so far as I can see) permitted, even though it should logically be identical.

Practically this means that although a naive compiler would be expected to just work, the optimizer may misbehave as in other UB.


NB. The thing that makes this hard to reason about is that a union and its members are pointer-interconvertible.
In general you'd think any A could really be the A member of some union AB { A a; B b; }, and converting to AB and thence to B* would be absolutely fine.

However, if the optimizer can ever prove this is not the case (as in your toy example), the standard gives it permission to go berserk.

February 16, 2026 Score: 3 Rep: 73 Quality: Low Completeness: 10%

This is undefined behavior in standard C++, even if all your static_assert pass.

Your checks only prove that the two types have the same size, alignment and memory layout but the C++ object model is stricter than just same size + same layout.

According standard, an object can only be accessed throught its own type.

On your code, A and B are diffferent and unrelated types.

So, accessing an object of type A throught a B* pointer breaks the strict aliasing rule.