我想了解一个奇怪的行为。我有以下代码:
union floatInt
{
float f;
unsigned int l;
};
floatInt A, B;
A.l = 0xFFA70B56;
B.f = A.f;
std::cout << std::hex << B.l << std::endl;
这工作正常,除了在 1 个配置中:非 Debug模式下的 Linux,然后我得到这个结果:ffe70b56
而且我真的不明白为什么值发生了变化。我已经通过几点来理解这一点:
-
It's undefined behavior to read from the member of the union that wasn't most recently written. Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union.
但是如果我们不能使用其他成员, union 的目的是什么?而且,它指向相同的内存位置,所以应该不会不同。
- 我使用的值 (0xFFA70B56) 是 IEEE 754 标准中的 NAN。那么,当它影响到另一个变量时,是否可以将其解释并更改为另一个 NAN 值,如 0xFFE70B56?
- 如果我将 B 声明为 volatile,则错误消失。请注意,该变量未在代码中的其他任何地方使用。那么它与编译器优化有关吗?
最佳答案
But what would be the purpose of a union if we cannot use the other members?
union的目的是在不同的时间使用相同的内存区域存储不同的对象,从而节省内存。
floatInt
占用的内存与float
变量占用的内存相同。
如果您的目标是使用 union ,我建议添加一个 bool 元素来跟踪使用了两个元素中的哪一个。
如果你想同时使用这两个属性,你应该使用 struct
或(我们在 c++ 中)class
有关 union 的更多信息,请阅读 here
关于C++ 将 NAN 值分配给 union 内的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39979696/