reinterpret_casting指向指针类型的整数并返回产生相同的值吗? [英] Does reinterpret_casting an integral to a pointer type and back yield the same value?

查看:84
本文介绍了reinterpret_casting指向指针类型的整数并返回产生相同的值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 http://en.cppreference.com/w/cpp/language/reinterpret_cast ,已知reinterpret_cast指向具有足够大小的整数并返回的指针会产生相同的值.我想知道标准是否也相反.也就是说,reinterpret_cast是否与足够大的指针类型的整数并向后产生相同的值?

According to http://en.cppreference.com/w/cpp/language/reinterpret_cast, it is known that reinterpret_cast a pointer to an integral of sufficient size and back yield the same value. I'm wondering whether the converse is also true by the standards. That is, does reinterpret_cast an integral to a pointer type of sufficient size and back yield the same value?

推荐答案

不,该标准不能保证.引用有关指针整数转换的C ++ 14(n4140)[expr.reinterpret.cast]的所有部分,重点是我的:

No, that is not guaranteed by the standard. Quoting all parts of C++14 (n4140) [expr.reinterpret.cast] which concern pointer–integer conversions, emphasis mine:

4可以将指针显式转换为足够大以容纳指针的任何整数类型.映射功能是 实现定义的. [注意:对于那些知道地址结构的人来说,这并不奇怪 基础机器的. -尾注] ...

4 A pointer can be explicitly converted to any integral type large enough to hold it. The mapping function is implementation-defined. [ Note: It is intended to be unsurprising to those who know the addressing structure of the underlying machine. —end note ] ...

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

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 3.7.4.3, the result of such a conversion will not be a safely-derived pointer value. —end note ]

因此,从整数值开始并将其转换为指针并返回(假定没有大小问题)是实现定义的.这意味着您必须查阅编译器的文档,以了解这种往返是否保留值.因此,它肯定不是便携式的.

So starting with an integral value and converting it to a pointer and back (assuming no size issues) is implementation-defined. Which means you must consult your compiler's documentation to learn whether such a round trip preserves values or not. As such, it is certainly not portable.

这篇关于reinterpret_casting指向指针类型的整数并返回产生相同的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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