問題描述
將指針轉換為 int 然后再轉換回指針是否安全?
Is it safe to cast pointer to int and later back to pointer again?
如果我們知道指針是 32 位長,int 是 32 位長呢?
How about if we know if the pointer is 32 bit long and int is 32 bit long?
long* juggle(long* p) {
static_assert(sizeof(long*) == sizeof(int));
int v = reinterpret_cast<int>(p); // or if sizeof(*)==8 choose long here
do_some_math(v); // prevent compiler from optimizing
return reinterpret_cast<long*>(v);
}
int main() {
long* stuff = new long(42);
long* ffuts = juggle(stuff);
std::cout << "Is this always 42? " << *ffuts << std::endl;
}
這是否包含在標準中?
推薦答案
沒有
例如,在 x86-64 上,一個指針是 64 位長,但 int
只有 32 位長.將指針轉換為 int 并再次返回會使指針值的高 32 位丟失.
For instance, on x86-64, a pointer is 64-bit long, but int
is only 32-bit long. Casting a pointer to int and back again makes the upper 32-bit of the pointer value lost.
如果你想要一個保證與指針一樣長的整數類型,你可以在
中使用 intptr_t
類型.您可以安全地從指向 intptr_t
的指針重新解釋轉換并返回.
You may use the intptr_t
type in <cstdint>
if you want an integer type which is guaranteed to be as long as the pointer. You could safely reinterpret_cast from a pointer to an intptr_t
and back.
這篇關于C++:將指針轉換為 int 然后再轉換回指針是否安全?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!