随笔 - 505  文章 - 1034  trackbacks - 0
<2007年9月>
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456


子曾经曰过:编程无他,唯手熟尔!

常用链接

留言簿(94)

随笔分类(649)

随笔档案(505)

相册

BCB

Crytek

  • crymod
  • Crytek's Offical Modding Portal

Game Industry

OGRE

other

Programmers

Qt

WOW Stuff

搜索

  •  

积分与排名

  • 积分 - 894883
  • 排名 - 14

最新随笔

最新评论

阅读排行榜

评论排行榜


static_cast  与 reinterpret_cast   

  reinterpret_cast是为了映射到一个完全不同类型的意思,这个关键词在我们需要把类型映射回原有类型时用到它。我们映射到的类型仅仅是为了故弄玄虚和其他目的,这是所有映射中最危险的。(这句话是C++编程思想中的原话)

  static_cast 和 reinterpret_cast 操作符修改了操作数类型。它们不是互逆的; static_cast 在编译时使用类型信息执行转换,在转换执行必要的检测(诸如指针越界计算, 类型检查). 其操作数相对是安全的。另一方面;reinterpret_cast 仅仅是重新解释了给出的对象的比特模型而没有进行二进制转换, 例子如下:

  int n=9; double d=static_cast < double > (n);

  上面的例子中, 我们将一个变量从 int 转换到 double。 这些类型的二进制表达式是不同的。 要将整数 9 转换到 双精度整数 9,static_cast 需要正确地为双精度整数 d 补足比特位。其结果为 9.0。而reinterpret_cast 的行为却不同:

  int n=9;

  double d = reinterpret_cast<double  * > (n);

  这次, 结果有所不同. 在进行计算以后, d 包含无用值. 这是因为 reinterpret_cast 仅仅是复制 n 的比特位到 d, 没有进行必要的分析.

  因此, 你需要谨慎使用 reinterpret_cast.



Allows any pointer to be converted into any other pointer type. Also allows any integral type to be converted into any pointer type and vice versa.
One practical use of reinterpret_cast is in a hash function, which maps a value to an index in such a way that two distinct values rarely end up with the same index.
http://msdn.microsoft.com/en-us/library/e0w9f63b.aspx


// 02_reinterpret_cast.cpp : 定义控制台应用程序的入口点。
//

#include 
"stdafx.h"
#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 );
    
return ( unsigned short )( val ^ (val >> 16));
}

int _tmain(int argc, _TCHAR* argv[])
{
    
int* pInt = NULL;
    
// 把负数解释为地址
    pInt = reinterpret_cast<int*>(-0x0024FFE4); 
    cout 
<< pInt << endl; // FFDB001C 地址
    
// 4292542492,其十六进制表示正是FFDB001C
    cout << reinterpret_cast<unsigned int>(pInt) << endl; 
    cout 
<< UINT_MAX << endl; // 4294967295

    
int iValue = 9;
    
int* pValue = &iValue;
    cout 
<< &iValue << endl; // 0012FF1C 地址
    cout << pValue << endl;  // 0012FF1C 地址
    cout << *pValue << endl;  // 9 值

    cout 
<< reinterpret_cast<double*>(iValue) << endl; // 00000009 把iValue当作指针了
    cout << reinterpret_cast<double*>(pValue) << endl; // 0012FF1C 地址

    
int a[20];
    
for ( int i = 0; i < 20; i++ )
        cout 
<< Hash( a + i ) << endl;

    
return 0;
}
/* 输出:
FFDB001C
4292542492
4294967295
0012FF1C
0012FF1C
9
00000009
0012FF1C
65194
65198
65234
65238
65242
65246
65218
65222
65226
65230
65266
65270
65274
65278
65250
65254
65258
65262
65298
65302

*/
posted on 2011-02-16 20:00 七星重剑 阅读(2469) 评论(0)  编辑 收藏 引用 所属分类: PL--c/c++

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理