Is union a standard layout?

If I have a standard layout type, for example:

struct sl_t { int a; }; 

And such a union:

 union un_t { int b; double q; }; 

Can I use and use union as a type of structure? That is, can I assume that the union itself is a standard layout, and the data is aligned at the beginning of the memory?

 un_t obj; sl_t * s = reinterpret_cast<sl_t*>(&obj); s->a = 15; assert( obj.b == 15 ); 

Or should I take the address of the variable in the &obj.b ?

Note that I already know that if I store the structure inside the union, then the C ++ 11 standard ensures that I can access sl_t :: a and un_t :: b, referring to 9.5-1.

+4
source share
1 answer

Alignment seems to be your problem, check out the pragma pack . The struct / union names simply refer to the allocated memory block, if st_t.a is shifted in the structure, adding more members, your tide will fail, but if it remains the first member, it will work, since all members of the union point to the same address. as the union itself.

See C ++ Standard Section 9.2.17-21: “A pointer to a standard layout structure object properly converted using reinterpret_cast indicates its initial member (or if this element is a bit field, and then to the unit in which it located) and vice versa. "

See also section 9.5 Unions: 1. In a union, no more than one non-static data element can be active at any time, that is, the value of no more than one of the non-static data elements can be stored in the union at any time. [Note. To simplify the use of joins, there is one special guarantee: if the union of the standard layout contains several standard layout structures that have a common initial sequence (9.2), and if the object of this type of standard layout contains one of the standard layout structures, it is allowed to check the general initial sequence of any of the elements standard layout structures, see 9.2. - end note). The size of the union is sufficient to contain the largest of its non-static data. Each member of the non-static data is distributed as if it were the only member of the structure. "

+3
source

Source: https://habr.com/ru/post/1382140/


All Articles