[英]Why can't I static_cast between char * and unsigned char *?
[英]Why is this an error: static_cast<unsigned*>(&i)
按照經驗法則static_cast
選擇static_cast
或dynamic_cast
,我編寫了以下程序:
int main(void)
{
int i = 0;
unsigned *j = static_cast<unsigned*>(&i);
return 0;
}
但是,它甚至沒有編譯:
$ g++ --std=c++11 test5.cpp
test5.cpp: In function ‘int main()’:
test5.cpp:4:44: error: invalid static_cast from type ‘int*’ to type ‘unsigned int*’
unsigned *j = static_cast<unsigned*>(&i);
^
為什么這是錯的? 這種情況的正確演員是什么?
您可以將static_cast
從int
轉換為unsigned
,從而執行適當的轉換。 但你擁有的是一個指針; 此指針指向要解釋為int
的內存區域。 取消引用指針會產生int
的值。 static_cast
不會在指向不相關類型的指針之間進行轉換 。
int i = 0;
int* ip = &i;
int j = *ip; // treat the region pointed to as an int
要在取消引用下將內存視為unsigned
,您需要重新解釋內存; 這就是reinterpret_cast
作用。
int i = 0;
int* ip = &i;
unsigned j = *reinterpret_cast<unsigned*>(ip); // treat the region pointed to as unsigned
但是,你不應該這樣做。 reinterpret_cast
完全按照它的說法完成:將內存重新解釋為不同的類型。 如果位模式與該類型的預期不匹配,則結果將與static_cast<unsigned>
執行的轉換不同。 例如,在沒有使用2的補碼表示有符號整數的系統中就是這種情況。
正確的方法是取消引用int*
then static_cast<unsigned>
結果:
int i = 0;
int* ip = &i;
unsigned j = static_cast<unsigned>(*ip); // treat the region pointed to as int
// then convert the int to unsigned
總結一下: static_cast
將執行整數轉換,但不會將內存區域重新解釋為不同的類型。 這就是reinterpret_cast
的用途。
你必須使用:
unsigned *j = static_cast<unsigned*>(static_cast<void*>(&i));
這是你可以讀到這里點5,或簡單地使用: reinterpret_cast的 :
int i = 0;
unsigned *j = reinterpret_cast<unsigned*>(&i);
通常不使用cast-s程序員使用聯合如下:
union {
int n;
unsigned char bt[4];
} data;
data.n = i;
data.bt[3] = 0xff;
正如在評論中所說的那樣,使用union進行強制轉換是未定義的行為 - 即使它得到了大多數編譯器的支持:你可以在這里閱讀更多內容: 是否使用了union來代替定義好的強制轉換? 在這里使用一個聯合代替一個定義好的演員?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.