在 void 指针中存储整数的往返安全性

Round-trip safety of storing integer in void pointer

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 ]

因此,虽然从指针到整数的映射保证有左逆(因此是单射的),但不能保证它是双射的;它是否是 "implementation-defined" 行为的一部分。正如 cppreference 指出的那样,可能有几个整数转换为同一个指针。

可能没有与平台地址宽度完全匹配的整数类型space。 intptr_t 必须足够大以容纳任何指针值,这意味着它与指针一样大或更大,当它更大时,鸽巢原理保证不可能每个整数值都有唯一的 void* 值。