reinterpret_cast 运算符

允许将任何指针转换为任何其他指针类型。 也允许将任何整数类型转换为任何指针类型以及反向转换。
语法:
reinterpret_cast < type-id > ( expression )

备注:
滥用 reinterpret_cast 运算符可能很容易带来风险。 除非所需转换本身是低级别的,否则应使用其他强制转换运算符之一。

reinterpret_cast 运算符可用于 char* 到 int* 或 One_class* 到 Unrelated_class* 之类的转换,这本身并不安全。

reinterpret_cast 的结果不能安全地用于除强制转换回其原始类型以外的任何用途。 在最好的情况下,其他用途也是不可移植的。

reinterpret_cast 运算符无法强制转换掉 const、volatile 或 __unaligned 特性。 有关移除这些特性的详细信息,请参阅 const_cast Operator。

reinterpret_cast 运算符将空指针值转换为目标类型的空指针值。

reinterpret_cast 的一个实际用途是在哈希函数中,即,通过让两个不同的值几乎不以相同的索引结尾的方式将值映射到索引。

点击查看代码
#include<iostream>
using namespace std;

// Returns a hash code based on an address
unsigned short Hash(void* p) {
	unsigned int val = reinterpret_cast<unsigned int>(p);
	cout << "val=" << val << endl;
	return (unsigned short)(val ^ (val >> 16));
}
int main() {
	int a[20];
	for (int i = 0; i < 20; i++)
	{
		cout << "a+i:" << a + i << endl;
		cout << Hash(a + i) << endl;

	}

}

转自:
https://learn.microsoft.com/zh-cn/cpp/cpp/reinterpret-cast-operator?view=msvc-140

posted @ 2024-10-21 17:03  阳光天气  阅读(36)  评论(0编辑  收藏  举报