c++ - 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++17 12.2.4 Bit-fields /1
(C++11 9.6 Bit-fields /1
就此而言,如果您想要特定于您选择的标签的答案):
类对象内的位域分配是实现定义的。位域的对齐是实现定义的。位域被打包到一些可寻址的分配单元中。[注意:位域在某些机器上跨越分配单元,而不在其他机器上。位域在某些机器上从右到左分配,在其他机器上从左到右分配。- 结束注]
依赖于实现定义的行为,就其本质而言,意味着不可移植的代码。
推荐阅读
- r-markdown - “papaja”:标题页底部的“作者注释”标题
- php - 如何拆分 php dom 元素上的节点值
- python - matplotlib plot 会导致 sklearn 的 PCA.fit_transform 函数失败吗?
- android - Android:MVVM - RecyclerView 动态数据加载
- google-apps-script - 如何从Google工作表中存在上标的单元格中的句子中获取文本
- r - 用 ggrepel 和抖动点标记多面图
- c# - C# 数据注释未显示正确的显示名称
- flask - 如何使 WTForms 中的两个 FormField 中的至少一个成为必需的?
- java - 为最后一次出现的字符拆分字符串
- javascript - 如何在 Sequelize 中生成 12 位唯一 ID?