问题描述
将指针转换为 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 然后再转换回指针是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!