简体   繁体   English

C ++联合/结构位域实现和可移植性

[英]C++ Union/Struct Bitfield Implementation and Portability

I have a union containing a uint16 and a struct like so: 我有一个包含uint16和这样的结构的联合:

union pData {
    uint16_t w1;
    struct {
        uint8_t d1 : 8;
        uint8_t d2 : 4;
        bool b1 : 1;
        bool b2 : 1;
        bool b3 : 1;
        bool b4 : 1;
    } bits;
};

My colleague says there is an issue with this being portable, but I am not sure I buy this. 我的同事说,这种便携式产品存在问题,但是我不确定我是否会购买。 Could some please explain (simple as possible) what is "wrong" here? 可以请一些人解释(尽可能简单)什么是“错误的”吗?

From C++17 12.2.4 Bit-fields /1 (and C++11 9.6 Bit-fields /1 for that matter, if you want the answer specific to your chosen tags): C++17 12.2.4 Bit-fields /1 (和C++11 9.6 Bit-fields /1 ,如果您想要特定于所选标签的答案):

Allocation of bit-fields within a class object is implementation-defined. 类对象内的位域分配由实现定义。 Alignment of bit-fields is implementation-defined. 位域的对齐是实现定义的。 Bit-fields are packed into some addressable allocation unit. 位字段打包到一些可寻址的分配单元中。 [Note: Bit-fields straddle allocation units on some machines and not on others. [注意:位域跨越某些机器上的分配单元, 而不是在其他机器上。 Bit-fields are assigned right-to-left on some machines, left-to-right on others. 在某些计算机上,位字段是从右到左分配的,在其他计算机上从左到右分配的 - end note] -尾注]

Reliance on implementation defined behaviour means, by its very nature, non-portable code. 依赖于实现定义的行为,就其本质而言,意味着不可移植的代码。

Maybe your colleague guesses that you intend to write to w1 and read from bits or vice versa. 也许您的同事猜测您打算写入w1并从bits读取,反之亦然。

That would be undefined behaviour. 那将是不确定的行为。 In C++ only one member of a union can be active at any one time; 在C ++中, union只有一个成员可以随时处于活动状态 writing a member makes it active, and the behaviour of reading an inactive member is undefined. 写入成员使其处于活动状态,而读取非活动成员的行为是不确定的。

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

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