大家使用的时候千万记住,不要乱使用!错误使用很容易导致程序的不安全!
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; }
对于强制类型转换,他们各有各的用途,但是不要去频繁使用他们,每次使用前我们可以尝试是否有其他方法能达到相同的目的,如果必须使用,那么我们要强制转换的作用域,并且记录所有假定涉及的类型,可以减少错误的发生!
2012/8/7
jofranks 于南昌