c++ - 字段联合和结构联合之间的区别
问题描述
我正在定义一组结构来处理一些寄存器,当我定义结构时,我发现定义简单字段的联合和结构的联合之间存在这种差异。我不确定为什么会发生这种差异:
#include <iostream>
using namespace std;
typedef union
{
uint16_t all_bits;
struct
{
uint16_t a:4, b:4, c:4, d:3, e:1;
};
}
Example1_t;
typedef union
{
uint16_t all_bits;
uint16_t a:4, b:4, c:4, d:3, e:1;
}
Example2_t;
int
main ()
{
Example1_t example1;
Example2_t example2;
example1.all_bits = 0x8BCD;
example2.all_bits = 0x8BCD;
cout << "a " << std::hex << example1.a << " " << example2.a << std::endl;
cout << "b " << std::hex << example1.b << " " << example2.b << std::endl;
cout << "c " << std::hex << example1.c << " " << example2.c << std::endl;
cout << "d " << std::hex << example1.d << " " << example2.d << std::endl;
cout << "e " << std::hex << example1.e << " " << example2.e << std::endl;
return 0;
}
输出:
添加
bcd
cbd
d 0 5
e 1 1
解决方案
迂腐的答案是:
您的代码具有未定义的行为。写入联合字段并从另一个字段读取并不能保证有效,因此您看到的任何不一致都可以作为“损坏的代码”手动消除。
实际上,很多人都依赖于这种“破坏行为”的一致性,以至于所有现代编译器仍然在这里提供可预测的功能(以忽略一些优化机会为代价)。因此,您的代码中确实有一些特定的东西使它的行为方式如下:
在Example1_t
中,联合有两个重叠all_bits
的字段:和结构。在该结构中,每个成员都有不同的存储空间。
在Example2_t
, a
, b
, c
,d
和e
都是并集的独立字段,所以它们都有重叠存储。
推荐阅读
- python - 当列行值匹配条件时迭代数据框的 Pythonic 方法
- c++ - Dev cpp - 运行时出错:不是有效的 Win32 应用程序
- android - 通过几个属性对 RecyclerView 元素进行分组
- python - 找不到 div 元素 - Selenium
- python-3.x - 无法使用 python 和 selenium 点击链接
- python - 用线图中的标记突出显示单个点
- python - 如何在不事先下载和转换的情况下将音频从 pytube 流式传输到 FFMPEG 和 discord.py
- python - 如何在 PyTorch 中找到混淆矩阵并为图像分类器绘制它
- c# - 如何在 blazor webassembly 应用程序(客户端)中调用 blazor 服务器应用程序(登录 webapi)
- wordpress - 如何使用 Wordpress REST API 按多个 id 获取分类列表?