c語(yǔ)言: Noncompliant Code Example(不兼容的代碼示例) The size of a pointer can be greater than the size of an integer, such as in an implementation where pointers are 64 bits and unsigned integers are 32 bits. This code example is noncompliant on such implementations because the result of converting the 64-bit ptr cannot be represented in the 32-bit integer type: void f(void) { char *ptr; /* ... */ unsigned int number = (unsigned int)ptr; /* ... */ } Compliant Solution(兼容的代碼示例) Any valid pointer to void can be converted to intptr_t or uintptr_t and back with no change in value (seeINT36-EX2). The C Standard guarantees that a pointer to void may be converted to or from a pointer to any object type and back again and that the result must compare equal to the original pointer. Consequently, converting directly from a char * pointer to a uintptr_t, as in this compliant solution, is allowed on implementations that support the uintptr_t type. #include void f(void) { char *ptr; /* ... */ uintptr_t number = (uintptr_t)ptr; /* ... */ } 使用intptr_t和uintptr_t才是兼容的,就死一套代碼同時(shí)兼容32位和64位的操作系統(tǒng)。
intptr_t和uintptr_t 這兩個(gè)數(shù)據(jù)類型是ISO C99定義的,具體代碼在linux平臺(tái)的/usr/include/stdint.h頭文件中。 該頭文件中定義intptr_t和uintptr_t這兩個(gè)數(shù)據(jù)類型的代碼片段如下: /* Types for `void *' pointers. */ 在64位的機(jī)器上,intptr_t和uintptr_t分別是long int、unsigned long int的別名;在32位的機(jī)器上,intptr_t和uintptr_t分別是int、unsigned int的別名。 那么為什么要用typedef定義新的別名呢?我想主要是為了提高程序的可移植性(在32位和64位的機(jī)器上)。很明顯,上述代碼會(huì)根據(jù)宿主機(jī)器的位數(shù)為intptr_t和uintptr_t適配相應(yīng)的數(shù)據(jù)類型。
c++語(yǔ)言: reinterpret_cast<type-id> (expression) type-id 必須是一個(gè)指針、引用、算術(shù)類型、函數(shù)指針或者成員指針。它可以把一個(gè)指針轉(zhuǎn)換成一個(gè)整數(shù),也可以把一個(gè)整數(shù)轉(zhuǎn)換成一個(gè)指針(先把一個(gè)指針轉(zhuǎn)換成一個(gè)整數(shù),再把該整數(shù)轉(zhuǎn)換成原類型的指針,還可以得到原先的指針值)。 type-id是轉(zhuǎn)換后的類型,expresion是轉(zhuǎn)換前的。
static_cast 與 reinterpret_cast reinterpret_cast是為了映射到一個(gè)完全不同類型的意思,這個(gè)關(guān)鍵詞在我們需要把類型映射回原有類型時(shí)用到它。我們映射到的類型僅僅是為了故弄玄虛和其他目的,這是所有映射中最危險(xiǎn)的。(這句話是C++編程思想中的原話) static_cast和reinterpret_cast的區(qū)別主要在于多重繼承,比如
那么對(duì)于以下代碼:
前兩個(gè)的輸出值是相同的,最后一個(gè)則會(huì)在原基礎(chǔ)上偏移4個(gè)字節(jié),這是因?yàn)?a >static_cast計(jì)算了父子類指針轉(zhuǎn)換的偏移量,并將之轉(zhuǎn)換到正確的地址(c里面有m_a,m_b,轉(zhuǎn)換為B*指針后指到m_b處),而reinterpret_cast卻不會(huì)做這一層轉(zhuǎn)換。 總結(jié):reinterpret_cast用于指針和整型之間的轉(zhuǎn)換是沒(méi)有問(wèn)題,如果用于子類和父類類型方面的轉(zhuǎn)換,會(huì)有問(wèn)題。如果需要在子類和父類指針之間的轉(zhuǎn)換,要用static_cast。 |
|