C++中的類型轉換——reinterpret_cast


reinterpret_cast 重新解釋類型

此外.....內存地址不變

 

 

 

 

 

 

 

 

 https://blog.csdn.net/wangshubo1989/article/details/49133667

reinterpret_cast作用為:
允許將任何指針轉換為任何其他指針類型。 也允許將任何整數類型轉換為任何指針類型以及反向轉換。

看着上面的描述就有種放浪形骸的趕腳。更會讓人不寒而栗,太隨意!

語法還是老樣子:
reinterpret_cast < type-id > ( expression )

濫用 reinterpret_cast 運算符可能很容易帶來風險。 除非所需轉換本身是低級別的,否則應使用其他強制轉換運算符之一。

reinterpret_cast 運算符可用於 char* 到 int* 或 One_class* 到 Unrelated_class* 之類的轉換,這本身並不安全。

reinterpret_cast 的結果不能安全地用於除強制轉換回其原始類型以外的任何用途。 在最好的情況下,其他用途也是不可移植的。

reinterpret_cast 運算符不能丟掉 const、volatile 或 __unaligned 特性。 有關移除這些特性的詳細信息,請參閱 const_cast Operator。

reinterpret_cast 運算符將 null 指針值轉換為目標類型的 null 指針值。
reinterpret_cast 的一個實際用途是在哈希函數中,即,通過讓兩個不同的值幾乎不以相同的索引結尾的方式將值映射到索引。(我也不懂,求指導)
msdn上給的代碼

#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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM