C++:将指针转换为 int 然后再转换回指针是否安全?

C++: Is it safe to cast pointer to int and later back to pointer again?(C++:将指针转换为 int 然后再转换回指针是否安全?)
本文介绍了C++:将指针转换为 int 然后再转换回指针是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)