Round-trip safety of storing integer in void pointer

前端 未结 2 752
余生分开走
余生分开走 2021-01-19 15:00

In this article the following is mentioned regarding reinterpret_cast of integers and pointers:

(the round-trip conversi

相关标签:
2条回答
  • 2021-01-19 15:31

    There might not be an integral type that exactly matches the width of the platform's address space. intptr_t has to be big enough to hold any pointer value, meaning it is as big or bigger than a pointer, and when it is bigger, the pigeonhole principle guarantees that it won't be possible for each integer value to have a unique void* value.

    0 讨论(0)
  • 2021-01-19 15:36

    Your interpretation is correct. The relevant paragraph of the standard is [expr.reinterpret.cast]/5 in C++17:

    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 ]

    Thus, while the mapping from pointers to integers is guaranteed to have a left inverse (and therefore be injective), no guarantee is made that it is bijective; whether or not it is part of the "implementation-defined" behaviour. As cppreference points out, there may be several integers that convert to the same pointer.

    0 讨论(0)
提交回复
热议问题