C ++:将指针转换为int和稍后再次返回指针是安全的吗? [英] C++: Is it safe to cast pointer to int and later back to pointer again?

查看:116
本文介绍了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 键入< cstdint> 如果你想要一个整数类型,保证只要指针。你可以安全地从指针指向 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和稍后再次返回指针是安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆