C++: Is it safe to cast pointer to int and later back to pointer again?(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 然后再转换回指针是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++:将指针转换为 int 然后再转换回指针是否安全
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
