如何在C++中使用reinterpret_cast?

sun*_*t07 18 c++

我知道C++中的reinterpret_cast可以这样使用:

float a = 0;
int b = *reinterpret_cast<int*>(&a);
Run Code Online (Sandbox Code Playgroud)

但是为什么不能直接施展呢?

float a = 0;
int b = reinterpret_cast<int>(a);

error: invalid cast from type 'float' to type 'int'
Run Code Online (Sandbox Code Playgroud)

Cae*_*sar 35

一切reinterpret_cast都是允许您以不同的方式读取您传递的内存.你给它一个内存位置,你要求它读取内存,就好像它是你要求的那样.这就是为什么它只能用于指针和引用.

我们以此代码为例:

#include <iostream>

int main()
{
    float a = 12;
    int b = *reinterpret_cast<int*>(&a);

    std::cout << b;
}
Run Code Online (Sandbox Code Playgroud)

所以要将这行代码分解为更多细节*reinterpret_cast<int*>(&a);:

  1. 取地址 a
  2. reinterpret_cast 到了 int*
  3. 回到int*那个指向的地方a
  4. 将返回指针的值推迟为 int

现在,当我运行这个时,我得到1094713344的原因是12,因为float使用IEEE表示为0100 0001 0100 0000 0000 0000 0000 0000二进制.现在把这个二进制文件读成它unsigned int,然后你最终得到1094713344.

这就是为什么reinterpret_cast被认为是非常危险的原因以及为什么不应该在这种情况下使用它.

只有当指针指向内存并且需要以某种方式读取该内存并且您知道可以以这种方式读取内存时,才应该使用它.

  • @ sunlight07`reinterpret_cast`允许你投射指针和引用.即使C++不希望你在这种情况下这样做,它们也不会阻止你.如果你真的想要,C++将允许你用脚射击自己. (6认同)

Kla*_*aim 10

在你给出的情况下你不能reinterpret_cast因为reinterpret_cast只接受一个int来转换为一个指针,反之亦然,并遵循其他类似的规则.

这里有这些规则的摘要:http://en.cppreference.com/w/cpp/language/reinterpret_cast