详解C++中const_cast与reinterpret_cast运算符的用法

2020-01-06 14:19:56刘景俊
  • reinterpret_cast 运算符不能丢掉 const、volatile 或 __unaligned 特性。有关移除这些特性的详细信息,请参阅 const_cast Operator。
  • reinterpret_cast 运算符将 null 指针值转换为目标类型的 null 指针值。
  • 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 );
      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;
    }
    
    

    Output: 

    
    64641
    64645
    64889
    64893
    64881
    64885
    64873
    64877
    64865
    64869
    64857
    64861
    64849
    64853
    64841
    64845
    64833
    64837
    64825
    64829
    

    reinterpret_cast 允许将指针视为整数类型。结果随后将按位移位并与自身进行“异或”运算以生成唯一的索引(具有唯一性的概率非常高)。该索引随后被标准 C 样式强制转换截断为函数的返回类型。



    注:相关教程知识阅读请移步到C++教程频道。