在void指针中存储整数的往返安全性 [英] Round-trip safety of storing integer in void pointer

查看:59
本文介绍了在void指针中存储整数的往返安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章中,以下提到了有关 整型和指针的reinterpret_cast :

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

(不保证在相反方向上的往返转换;同一指针可能具有多个整数表示形式)

(the round-trip conversion in the opposite direction is not guaranteed; the same pointer may have multiple integer representations)

我是否正确理解标准并不能保证以下内容?

Do I understand correctly that the following is then not guaranteed by the standard:

intptr_t x = 5; 
void* y = reinterpret_cast<void*>(x);
assert(x == reinterpret_cast<intptr_t>(y));

有人可以确认吗?

推荐答案

您的解释正确.该标准的相关段落为C ++ 17中的[expr.reinterpret.cast]/5:

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

可以将整数类型或枚举类型的值显式转换为指针.指针转换为一个足够大的整数(如果实现中存在这样的整数)并返回相同的指针类型将具有其原始价值;指针和整数之间的映射否则由实现定义.[注意:除6.7.4.3中所述外,此类转换的结果不会是安全得出的指针价值.— 尾注]

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指出的那样,可能会有多个整数转换为相同的指针.

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.

这篇关于在void指针中存储整数的往返安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆