c++ - reinterpret_casting 一个指针类型的整数和返回是否产生相同的值?

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

根据 http://en.cppreference.com/w/cpp/language/reinterpret_cast ,众所周知,reinterpret_cast 是一个指向足够大的整数的指针,并且返回相同的值。我想知道反过来是否也符合标准。也就是说,reinterpret_cast 是否是具有足够大小的指针类型的整数并返回相同的值?

最佳答案

不,标准不保证这一点。引用 C++14 (n4140) [expr.reinterpret.cast] 中涉及指针-整数转换的所有部分,强调我的:

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 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 ]

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

关于c++ - reinterpret_casting 一个指针类型的整数和返回是否产生相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28979126/

相关文章:

c++ - 操作 "false < true"是否定义明确?

c++ - 为什么以下两个程序会产生不同的输出? (C++,位操作,VS 2012)

c++ - 如何隐藏 dll 导出类中的成员变量

c++ - 输出不打印?

c++ - 使用 GoogleTest 访问私有(private)成员

c - 为什么 getline 在 C 函数中失败?

c - 使用指针获取数组的长度

C - 获取字符串的指针地址

c++ - 定义 uint64_t 常量的最佳/正确方法

C++:const static DEBUG 和 if 语句,实际的执行时间开销是多少?