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

标签 c++ pointers language-lawyer reinterpret-cast

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/

相关文章:

c++ - 使用指针成员变量重载类中的 + 运算符

c++ - return *this 在 C++ 中安全吗?

c++ - 带引用的 std::tuple 无法在 clang 中编译,但不能在 gcc 中编译

c++ - C编译器如何执行这个printf语句?

c++ - 如何在 Windows 上用 Vim 运行 “:compiler msvc” 和 “:comp msbuild”?

c - 指针数组更改值,使用 malloc 将内存分配给其他指针时

c++ - std::atomic 内存屏障可以用于在线程之间传输非原子数据吗?

c - 一维访问多维数组 : is it well-defined behaviour?

c++ - 为什么 ADL 优先于 'std namespace' 中的函数,但等于用户定义的命名空间中的函数?

java - C++和Java中的异常处理之间的区别?