首页 > 解决方案 > C++ Union/Struct Bitfield Implementation and Portability

问题描述

I have a union containing a uint16 and a struct like so:

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?

标签: c++c++11structunions

解决方案


来自C++17 12.2.4 Bit-fields /1C++11 9.6 Bit-fields /1就此而言,如果您想要特定于您选择的标签的答案):

类对象内的位域分配是实现定义的。位域的对齐是实现定义的。位域被打包到一些可寻址的分配单元中。[注意:位域在某些机器上跨越分配单元,而不在其他机器上。位域在某些机器上从右到左分配,在其他机器上从左到右分配。- 结束注]

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


推荐阅读