本文介绍了跨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;
}

memcpy的调用没有任何副作用,除了将i更改为与num相同的字节外.

there is no side effect from that call of memcpy other than changing i to have the same bytes as num did.

的确,编译器可以在此处自由插入对库memcpy函数的调用.他们还可以自由插入一百万个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.

这篇关于跨C和C ++标准进行可靠的类型处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 08:40