C/C++ 类型转换机制(三)重解释转换

重解释转换就是将两个毫无关联的类型之间的转换(比如把 int* 强转为 float*,或者把指针强转成整数)。它不改变底层内存的任何一个比特,只是强行换了一副“眼镜”来解读这段内存。

此外,它也可以用于 void* 和其他具体类型指针的转换。但需要注意,void* 作为通用指针,天然与其他指针存在关联,因此在 C++ 中,使用 static_cast 处理 void* 在语义上更加合适。在 C++ 中,这种暴力的重解释转换,由 reinterpret_cast 运算符全权负责。

1. 使用语法

#include <iostream>
#include <cstdint>
using namespace std;

void test()
{
    // 不相关指针、应用之间的转换
    int value = 100;
    int* ip = &value;
    char* cp = reinterpret_cast<char*>(ip);

    // 指针转整数:把地址当作整数来看待
    uintptr_t vi = reinterpret_cast<uintptr_t>(cp);

    // 整数转指针:把整数当做地址来看待
    short* sp = reinterpret_cast<short*>(vi);

    // 把 int 的内存,强行按 float 来读
    int& iref = value;
    float& fref = reinterpret_cast<float&>(iref);
    std::cout << fref << std::endl;

    // 当然,也可以用于 void* 和其他类型指针转换(更好的选择是 static_cast)
    void* vp = ip;
    long* lp = reinterpret_cast<long*>(vp);
}


int main()
{
    test();
    return 0;
}

2. 使用注意

reinterpret_cast 的职权范围非常死板:它只负责在指针、引用和足够大的整型这三者之间来回倒腾。只要超出了这个范围(比如基础类型、浮点型、带 const 的),它一概不管。

#include <iostream>
#include <cstdint>
using namespace std;


// 想一想:为什么转换失败?
void test()
{
	// 只能用于指针和指针、引用和引用、指针和整数之间的转换
	char a = 100;
	// int b = reinterpret_cast<int>(a);

	// 不能用于移除 const 的操作
	const int ci = 5;
	//int* p2 = reinterpret_cast<int*>(&ci);

	// 小数不能作为地址值
	double v = 3.14;
	//int* p = reinterpret_cast<int*>(v);


	//地址值也不能作为小数
	//int* p = &a;
	//double c = reinterpret_cast<double>(p);
}


int main()
{
    test();
    return 0;
}