c++ - union 的内存对齐问题

标签 c++ unions memory-alignment

如果我们在堆栈中创建这种类型的对象,是否可以保证该对象的内存将正确对齐?

union my_union
{
  int value;
  char bytes[4];
};

如果我们在堆栈中创建 char bytes[4] 然后尝试将其转换为整数,则可能存在对齐问题。我们可以通过在堆中创建它来避免这个问题,但是, union 对象有这样的保证吗?逻辑上应该有,但我想确认一下。

谢谢。

最佳答案

嗯,这取决于你的意思。

如果你的意思是:

Will both the int and char[4] members of the union be properly aligned so that I may use them independently of each other?

那么是的。如果你的意思是:

Will the int and char[4] members be guaranteed to be aligned to take up the same amount of space, so that I may access individual bytes of the int through the char[4]?

然后没有。这是因为 sizeof(int) 不能保证为 4。如果 int 是 2 个字节,那么谁知道哪两个 char 元素会对应于union中的int(标准没有指定)?

如果您想使用 union 来访问 int 的各个字节,请使用:

union {
  int i;
  char c[sizeof(int)];
};

由于每个成员的大小都相同,因此可以保证它们占据相同的空间。这就是我相信你想知道的,我希望我已经回答了。

关于c++ - union 的内存对齐问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4496423/

相关文章:

c++ - SDL 1.3 : how to inplement simple scale-9-grid for image resize?

c++ - 我怎样才能防止无名的结构\union ?

用于在 Intel Core 2 Duo 上对齐的 C 代码

c++ - 构建 64 位 dll 时为 "File contains invalid .pdata contributions"

c++ - 在 C++11 中将 reference_wrapper 对象作为函数参数传递

c++ - const 左值引用和右值引用之间的重载解析

C++ union 成员访问和未定义行为

c - 在 C 中的位域内格式化 union

c# - 为什么结构对齐取决于字段类型是原始类型还是用户定义的?

operator new 的 C++ 对齐,有多大关系?