C++ Union/Struct 位域实现和可移植性

C++ Union/Struct Bitfield Implementation and Portability

我有一个包含 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;
};

我的同事说这个便携性有问题,但我不确定我是否购买了这个。有人可以解释一下(尽可能简单)这里的 "wrong" 是什么吗?

来自 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]

依赖于实现定义的行为,就其本质而言,意味着不可移植的代码。

也许您的同事猜测您打算写入 w1 并从 bits 读取,反之亦然。

那将是未定义的行为。在 C++ 中,union 中只有一个成员可以在任何时候 active;写入一个成员使其活跃,而读取一个非活跃成员的行为是未定义的。