且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-17 20:51:16

没有

例如,在 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.