c++ - 我可以通过 reinterpret_cast 将 int 的空指针转换为 long 类型吗

标签 c++ type-conversion reinterpret-cast

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/

相关文章:

c++ - 处理多个文件时,我必须在 COleDropTarget::OnDrop() 中返回哪个值?

c++ - Const 与数组到指针的转换

vb.net - 将 GUID 转换为数字等效项

c++ - SFINAE 和 sizeof 与 constexpr

c++ - boost asio steady_timer 上的多个递归 async_wait

c++ - 从指向具有相同签名的函数的指针转换为函数指针,但参数的附加限定除外

c++ - 将 reinterpret_cast 输入重新解释为 std::unique_ptr 永远不会真正安全吗?

c++ - 将像素数组保存到 jpeg 图像文件 C++

C# Dynamics : Convert. ChangeType 与 Cast