如果我们在堆栈中创建这种类型的对象,是否可以保证该对象的内存将正确对齐?
union my_union
{
int value;
char bytes[4];
};
如果我们在堆栈中创建 char bytes[4] 然后尝试将其转换为整数,则可能存在对齐问题。我们可以通过在堆中创建它来避免这个问题,但是, union 对象有这样的保证吗?逻辑上应该有,但我想确认一下。
谢谢。
最佳答案
嗯,这取决于你的意思。
如果你的意思是:
Will both the
int
andchar[4]
members of the union be properly aligned so that I may use them independently of each other?
那么是的。如果你的意思是:
Will the
int
andchar[4]
members be guaranteed to be aligned to take up the same amount of space, so that I may access individual bytes of theint
through thechar[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/