我可以通过 reinterpret_cast 将 int 的空指针转换为 long 类型吗 [英] Can I convert a null pointer of int to a long type by reinterpret_cast

查看:33
本文介绍了我可以通过 reinterpret_cast 将 int 的空指针转换为 long 类型吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int *pt = 0;
long i = reinterpret_cast(pt);

我保证是0吗?这是定义明确的还是实现定义的?我检查了 c++ 标准,但它只说明

Is i guaranteed to be 0? Is this well defined or implementation-defined? I checked the c++ standard, but it only states that

指向数据对象或函数的指针(但不是指向成员的指针)可以转换为任何足够大的整数类型以包含它.

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 不指向任何数据对象.该规则适用于本案吗?

In this case, pt doesn't point to any data object. Does the rule apply to this case?

推荐答案

i 不一定是任何值.结果是实现定义的.

No, i is not necessarily any value. The result is implementation-defined.

在 C++ 中,指针的表示是实现定义的,包括空指针的表示.当您将整数值零分配给指针时,您将该指针设置为实现定义 空指针值,该值不一定是所有位为零.通过传递性,将该值转换为整数的结果是实现定义的.

The representation of pointers, in C++, is implementation-defined, including the representation of a null pointer. When you assign an integer value of zero to a pointer, you set that pointer to the implementation-defined null pointer value, which is not necessarily all-bits-zero. The result of casting that value to an integer is, by transitivity, implementation-defined.

不过,更麻烦的是,reinterpret_cast 完成的映射无论如何都是实现定义的.因此,即使空指针值全部为零,实现也可以自由地产生任何它想要的结果.您只能保证在回滚时获得原始值.

Even more troublesome, though, is that the mapping done by reinterpret_cast is implementation-defined anyway. So even if the null pointer value was all-bits-zero, an implementation is free to make the result whatever it wants. You're only guaranteed that you'll get the original value when you cast back.

话虽如此,您引用后的下一句包括注释:

That all said, the next sentence after your quote includes the note:

[ 注意:对于那些知道寻址结构的人来说并不奇怪底层机器.——结尾说明]

[ Note: It is intended to be unsurprising to those who know the addressing structure of the underlying machine. —end note ]

因此,即使不需要特定的映射,您也可以根据实际情况进行猜测.

So even though specific mappings are not required, pragmatically you can take an educated guess.

假设 long 足够大.在 C++0x 中使用 uintptr_t,可选择在 中定义.

Assuming long is large enough. In C++0x use uintptr_t, optionally defined in <cstddef>.

这篇关于我可以通过 reinterpret_cast 将 int 的空指针转换为 long 类型吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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