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

标签 c++ c++11 struct unions

我有一个包含 uint16 和结构的 union :

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;
};

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

最佳答案

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

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

关于C++ union/结构位域实现和可移植性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53074726/

相关文章:

c# - Pinvoke-使用指向指针参数的指针来调用函数

c++ - 在 OS X 上跨 C 堆栈帧传播 C++ 异常

C++ 将 DWORD_PTR* 字符串打印到文件

c++11 - std::array 的默认初始化?

c++ - 在没有代码重复的情况下将 C 函数包装在自动对象中

C++ 如何修复多重声明编译器错误

c - 如何在 C 的结构中使用函数指针?

c++ - 如何声明自引用模板 typedef

c++ - 如何知道来自文本文件的输入是否是 C++ 中的有效数字

c - 结构具有 union 时的意外大小