c++ - 为什么将指针强制转换为数字类型是不安全的?

标签 c++ c++11 pointers casting

考虑这段代码

T* pa = new T(13);
int address = reinterpret_cast<int>(pa);

其中 T 可以是任何内置类型。

1) 我不明白 reinterpret cast 有什么问题??

2) 这种转换会导致未定义行为的情况有哪些?

3) pa 是否总是包含内存地址的正确十进制表示形式?

最佳答案

I can not understand what's wrong with reinterpret cast here?

因为标准不要求 int 和指针具有相同的大小,因此您可能会因强制转换而丢失信息。

What are the cases when this kind of casting will lead to an undefined behavior?

当这是真的时:

1 << (sizeof(T*) * CHAR_BIT) > INT_MAX

那么地址的值可能不会填充到 int 中,这会调用未定义的行为。

Will pa always contain the correct decimal representation of a memory address ?

如果您使用 std::[u]intptr_t ,那么是的,因为这些类型保证能够保存指针的值。

关于c++ - 为什么将指针强制转换为数字类型是不安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46134295/

相关文章:

C++ 方法与类的链接

c - 从C中的共享库访问指针

c - 将数组传递给函数的语法

c++ - 从 const 用户定义类转换为 C++ 中的内置类型

c++ - 抽象类和 move 语义

c++ - 如何在 INSERT、Cassandra C++ 驱动程序中将值绑定(bind)到 TTL

c++ - C++多线程设置中服务器重新初始化的良好设计

c - 指针未更新

c++ - 使用 OpenCV 检测棋盘中的中国棋子

c++ - 如何将 unique_ptr 参数传递给构造函数或函数?