在this article关于整数和指针的 reinterpret_cast
提到了以下内容:
(the round-trip conversion in the opposite direction is not guaranteed; the same pointer may have multiple integer representations)
我的理解是否正确,标准不保证以下内容:
intptr_t x = 5;
void* y = reinterpret_cast<void*>(x);
assert(x == reinterpret_cast<intptr_t>(y));
有人可以确认吗?
最佳答案
您的解释是正确的。该标准的相关段落是 C++17 中的 [expr.reinterpret.cast]/5:
A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined. [ Note: Except as described in 6.7.4.3, the result of such a conversion will not be a safely-derived pointer value. — end note ]
因此,虽然从指针到整数的映射保证有左逆(因此是单射的),但不能保证它是双射的;它是否是“实现定义”行为的一部分。正如 cppreference 指出的那样,可能有几个整数转换为同一个指针。
关于c++ - 在 void 指针中存储整数的往返安全性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48044512/