考虑这段代码
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/