跨 C 和 C++ 标准的可靠类型双关语
有没有一种在 C 和 C++ 中都有效的类型双关语?最好是低开销,并避免琐碎的预处理器黑客攻击.
Is there a way to type-pun that is valid in both C and C++? Preferably low overhead, and avoiding trivial preprocessor hacks.
在 C89 中,我知道我可以这样做:
In C89, I know I can do something like this:
unsigned int float_bits(float num) {
return *(unsigned int *)#
}
但是这违反了 C99 的严格别名规则.所以像这样的东西可能在各种 C 标准中更便携:
However this violates C99's strict aliasing rule. So something like this might be more portable across the various C standards:
unsigned int float_bits(float num) {
union { float f; unsigned int i; } u;
u.f = num;
return u.i;
}
但我知道这不是有效的 C++,因为一次只有一个联合成员可以活动".C 和 C++ 给出的典型解决方案是这样的:
But I know that this is not valid C++, because only one member of a union can be "active" at a time. The typical solution given for both C and C++ is something like this:
unsigned int float_bits(float num) {
unsigned int i;
memcpy(&i, &num, sizeof(int));
return i;
}
但是,这依赖于编译器能够优化对 memcpy 的调用.memcpy 是唯一可以跨 C 和 C++ 标准移植的方法吗?
However, this relies on the compiler being able to optimize away the call to memcpy. Is memcpy the only method that is portable across C and C++ standards?
推荐答案
unsigned int float_bits(float num) {
unsigned int i;
memcpy(&i, &num, sizeof(int));
return i;
}
除了将 i
更改为与 num
相同的字节之外,调用 memcpy
没有副作用.
there is no side effect from that call of memcpy
other than changing i
to have the same bytes as num
did.
确实,编译器可以自由地在此处插入对库 memcpy
函数的调用.他们还可以自由插入 100 万个 NOOP,一个乒乓模拟 AI 训练课,并尝试寻找 Goldblach 猜想证明的证明空间.
It is true that compilers are free to insert a call to a library memcpy
function here. They are also free to insert 1 million NOOPs, a pong simulation AI training session, and try to seach the proof space for the goldblach's conjecture proof.
在某些时候你必须假设你的编译器不是敌对的.
At some point you have to presume your compiler isn't hostile.
每个体面的编译器都了解 memcpy 的作用.
Every decent compiler understands what memcpy does.
相关文章