-
Notifications
You must be signed in to change notification settings - Fork 15.2k
Description
template <typename Type>
struct __attribute__((packed)) packed_t { Type v; };
union {
packed_t<float> f;
packed_t<int> i;
} u = {{1.0f}};
auto a = u.i.v;
does this code have undefined behavior?
In a standard-layout union with an active member of struct type T1, it is permitted to read a non-static data member m of another union member of struct type T2 provided m is part of the common initial sequence of T1 and T2; the behavior is as if the corresponding member of T1 were nominated.
If a program attempts to access ([defns.access]) the stored value of an object through a glvalue through which it is not type-accessible, the behavior is undefined.
https://eel.is/c++draft/class.mem#general-30
https://eel.is/c++draft/class.prop#10
https://eel.is/c++draft/class.union#general-2
https://eel.is/c++draft/basic.lval#11.sentence-2
But packed structures don't exist in the C++ standard and are represented by a byte array (as I understand it). So, if the sizes of these types are the same, there shouldn't be any undefined behavior. It's also unclear how the program will behave if the sizes are different.
Does the common initial sequence rule apply here within structures for accessing their data members?