int *pt = 0;<br/>
long i = reinterpret_cast<long>(pt);
我保证为0吗?这是明确定义的还是实现定义的? 我检查了 c++ 标准,但它只说明了
A pointer to a data object or to a function (but not a pointer to member) can be converted to any integer type large enough to contain it.
在这种情况下,pt 不指向任何数据对象。该规则适用于这种情况吗?
最佳答案
否,i
不一定是任何值。结果是实现定义的。†
在 C++ 中,指针的表示是实现定义的,包括空指针的表示。当您将零整数值分配给指针时,您将该指针设置为实现定义 空指针值,该值不一定全为零。根据传递性,将该值转换为整数的结果是实现定义的。
不过,更麻烦的是 reinterpret_cast
完成的映射无论如何都是实现定义的。因此,即使空指针值全为零,实现也可以随意生成它想要的结果。您只能保证在回退时会获得原始值。
综上所述,您引述后的下一句包括注释:
[ Note: It is intended to be unsurprising to those who know the addressing structure of the underlying machine. —end note ]
因此,尽管不需要特定的映射,但从实用的角度来说,您可以进行有根据的猜测。
† 假设 long
足够大。在 C++0x 中使用 uintptr_t
,可选地在 <cstddef>
中定义.
关于c++ - 我可以通过 reinterpret_cast 将 int 的空指针转换为 long 类型吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5640748/