簡體   English   中英

整數和指針(大小相同和不同)之間的 reinterpret_cast

[英]reinterpret_cast between integers and pointers (of same and of different sizes)

關於reinterpret_cast ,有些事情我不明白。

以下來自cppreference的片段說明了整數值和指針之間的轉換。

  1. 任何整數或枚舉類型的值都可以轉換為指針類型。 轉換為足夠大小的 integer 並返回相同指針類型的指針保證具有其原始值,否則無法安全地取消引用結果指針(不保證相反方向的往返轉換;相同的指針可能有多個 integer 表示)null 指針常量 NULL 或 integer 零不保證產生目標類型的 null 指針值; 為此應使用 static_cast 或隱式轉換。

特別是,根據我對“相反方向的往返轉換”部分的理解,C++ 不能保證任何有關演員表的信息

uintptr_t x;
reinterpret_cast<uintptr_t>(reinterpret_cast<void *>(x)) // == x ?

如果有這樣的保證,看看相應的參考就好了。

我的第二個問題是關於以下內容的正確性:假設int x; int y; int x; int y; x == y為真,並且sizeof(int)嚴格小於sizeof(void *) 那么是否保證reinterpret_cast<void *>(x) == reinterpret_cast<void *>(y)為真?

直觀地,假設在物理 memory 中, x后面有一些垃圾字節, y后面也有一些垃圾字節。 然后通過測試reinterpret_cast<void *>(x) == reinterpret_cast<void *>(y)我們正在進行以下數值比較:

x garbage_x
==
y garbage_y

為了澄清,x 指的是 memory 中表達式reinterpret_cast<void *>(x)中值為 x 的部分,而garbage_x指的是 memory 的剩余部分。

作為另一種特殊情況,它與文字的行為是什么,比如reinterpret_cast<void *>(1) == reinterpret_cast<void *>(1)

這一定是對原始 x86 分段 memory 架構的倒退,其中指針表示為段和偏移量,並且多個指針值將 map 指向相同的實際 RAM 字節。

從 integer 到指針的轉換可能會使用某種方法為指針計算一些任意段和偏移量,然后將指針轉換回 integer 將產生完全不同的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM