reinterpret_cast <new_type> (expression)
reinterpret_cast是强制类型转换符!他是用来处理无关类型转换的,通常为操作数的位模式提供较低层次的重新解释!但是他仅仅是重新解释了给出的对象的比特模型,并没有进行二进制的转换!
他是用在任意的指针之间的转换,引用之间的转换,指针和足够大的int型之间的转换,整数到指针的转换,在家面的文章中将给出!
来看一个例子:
int *pi;
char *pc = reinterpret_cast<char*>(pi);
OK, 在这里你可以看到reinterpret_cast的强大作用,但是要注意的是,他并没有进行二进制的转换,pc指向的真实对象其实还是int的,不是char~
对于reinterpret_cast运算符要谨慎使用,下面给出一些使用的地方:
参考IBM C++
- A pointer to any integral type large enough to hold it
(指针转向足够大的整数类型) - A value of integral or enumeration type to a pointer
(从整形或者enum枚举类型转换为指针) - A pointer to a function to a pointer to a function of a different
type (从指向函数的指针转向另一个不同类型的指向函数的指针) - A pointer to an object to a pointer to an object of a different type
(从一个指向对象的指针转向另一个不同类型的指向对象的指针) - A pointer to a member to a pointer to a member of a different class
or type, if the types of the members are both function types or
object types (从一个指向成员的指针转向另一个指向类成员的指针!或者是类型,如果类型的成员和函数都是函数类型或者对象类型)
这些是IBM C++推荐给我们的使用方式!
reinterpret_cast是为了映射到一个完全不同类型的意思,这个关键词在我们需要把类型映射回原有类型时用到它。我们映射到的类型仅仅是为了故弄玄虚和其他目的,这是所有映射中最危险的。(这句话是C++编程思想中的原话)
大家使用的时候千万记住,不要乱使用!错误使用很容易导致程序的不安全!
Misuse of the reinterpret_cast operator can easily be unsafe. 这是MSDN 的原话!
当然reinterpret_cast对 const, volatile, or __unaligned 也是没有用处的!
MSDN 上面给了一个实际的用处:哈希函数辅助
// expre_reinterpret_cast_Operator.cpp
// compile with: /EHsc
#include <iostream>
// Returns a hash code based on an address
unsigned short Hash( void *p ) {
unsigned int val = reinterpret_cast<unsigned int>( p );
return ( unsigned short )( val ^ (val >> 16));
}
using namespace std;
int main() {
int a[20];
for ( int i = 0; i < 20; i++ )
cout << Hash( a + i ) << endl;
}
对于强制类型转换,他们各有各的用途,但是不要去频繁使用他们,每次使用前我们可以尝试是否有其他方法能达到相同的目的,如果必须使用,那么我们要限制强制转换的作用域,并且记录所有假定涉及的类型,可以减少错误的发生!