The essence reinterpret_cast

Look at the following code:

#include  < iostream >  
using   namespace  std;

void  main() 

    
int  i  =   875770417
    cout
<< i << "   " ;
    
char *  p  =  reinterpret_cast < char *> ( & i);
    
for ( int  j = 0 ; j < 4 ; j ++ )
        cout
<< p[j];
    cout
<< endl;

    
float  f  =   0.00000016688933 ;
    cout 
<< f << "   " ;
    p 
=  reinterpret_cast < char *> ( & f);
    
for (j = 0 ; j < 4 ; j ++ )
        cout
<< p[j];
    cout
<< endl;
}

We see whether it is an int or float type i f, after reinterpret_cast <char *> (& addr) conversion output are "1234"

This is because 875,770,417 and single-precision floating-type 0.00000016688933 integer, the data in memory represented from low to high followed by 0x31 0x32 0x33 0x34.

The same data indicate that, when you put it int type data, he is 875,770,417; you treat it as a float type data, it is .00000016688933, the key is to see how the compiler to interpret the data, that is, the problem of semantic expression .

So reinterpret_cast <char *> is converted to ignore the semantics of the original data, and give it back char * semantics. With this understanding there later, and then look like the following code to understand.

#include  < iostream >  
using   namespace  std;

void  main() 

    
char *  p  =   " 1234 " ;

    
int *  pi  =  reinterpret_cast < int *> (p);
    cout
<<* pi << endl;
}

Output is 875770417 (0x34333231, pay attention to low and high), is the inverse of the above, it is easy to understand.

A strange look.

#include  < iostream >  
using   namespace  std;

class  CData
{
public :
    CData(
int  a,  int  b)
    {
        val1 
=  a;
        val2 
=  b;
    }

private :
    
int  val1;
    
int  val2;
};

void  main() 

    CData data(
0x32313536 0x37383433 );

    
int *  pi  =  reinterpret_cast < int *> (( char * ) & data  +   2 );
    cout
<<* pi << endl;
}

pi指向哪里?指向CData类型数据data的内存地址偏移2个字节。也就是说指向CData::val1和CData::val2的中间。这不是乱指嘛!没错,就是乱指,我们仍然看到输出数据显示875770417。

        也就是说只要是个地址,reinterpret_cast都能转,不管原来数据是啥,甚至不是一个数据的开始。所以,请正确的使用它,用你希望的方式。



from:  http://blog.csdn.net/coding_hello/article/details/2211466   谢谢您对知识耐心的总结!很受用!

Guess you like

Origin blog.csdn.net/alss1923/article/details/78892832