简体   繁体   English

联合本身是标准布局类型吗?

[英]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? 我可以转换并使用union作为结构类型吗? 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 ? 或者我必须在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. 请注意,我已经知道如果我将结构存储在联合内部,C ++ 11标准保证我可以访问sl_t :: a和un_t :: b,参考9.5-1。

Seems alignment is your issue, look at pragma pack . 似乎对齐是你的问题,看看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. 结构/联合名称只引用分配的内存块,如果st_t.a在结构中通过添加更多成员而被替换,则转换将失败,但如果它仍然是第一个成员,则它将起作用,因为联合的所有成员都指向与union本身相同的地址。

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." 请参阅C ++标准的第9.2.17-21节:“指向标准布局结构对象的指针,使用reinterpret_cast进行适当转换,指向其初始成员(或者如果该成员是位字段,则指向单元它居住在其中,反之亦然。“

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." 另请参见第9.5节“联合:”1。在联合中,最多一个非静态数据成员可以随时处于活动状态,也就是说,至多一个非静态数据成员的值可以存储在任何时候的联合。[注意:为了简化联合的使用,我们做了一个特殊的保证:如果标准布局联合包含几个共享一个共同初始序列(9.2)的标准布局结构,并且如果一个对象是这个标准布局联合类型包含一个标准布局结构,允许检查任何标准布局结构成员的公共初始序列;参见9.2。 - end note]联合的大小足以包含最大的非静态数据成员。每个非静态数据成员都被分配,就像它是结构的唯一成员一样。“

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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