简体   繁体   中英

Is a union a standard-layout type itself?

If I have a standard layout type like this:

struct sl_t
{
  int a;
};

And a union like this:

union un_t
{
  int b;
  double q;
};

Can I cast and use the union as the struct type? That is, may I assume that the union itself is a standard-layout type and the data is aligned at the start of the memory?

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

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

Note that I'm already aware that if I store the struct inside the union the C++11 standard guarantees I may access both sl_t::a and un_t::b, referring to 9.5-1.

Seems alignment is your issue, look at pragma pack . The struct/union names just references the allocated memory-block, if st_t.a is displaced in the struct by adding more members, your cast will fail, but if it remains the first member it will work since all members of the union points to the same address as the union itself.

See section 9.2.17 - 21 of the C++-standard: "A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa."

See also section 9.5 Unions: "1. In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time. [ Note: One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members; see 9.2. — end note ] The size of a union is sufficient to contain the largest of its non-static data members. Each non-static data member is allocated as if it were the sole member of a struct."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM