我可以通过reinterpret_cast将int的空指针转换为long类型吗
int *pt = 0;
long i = reinterpret_cast
i 保证为 0 吗?这是明确定义的还是实现定义的? 我检查了 c++ 标准,但它只指出
指向数据对象或函数的指针(但不是指向成员的指针)可以转换为任何足够大以包含它的整数类型。
在这种情况下, pt 不指向任何数据对象。该规则适用于本案吗?
int *pt = 0;
long i = reinterpret_cast<long>(pt);
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.
In this case, pt doesn't point to any data object. Does the rule apply to this case?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,
i
不一定是任何值。结果是实现定义的。†C++ 中指针的表示是实现定义的,包括空指针的表示。当您将整数值零分配给指针时,您将该指针设置为实现定义空指针值,该值不一定是全位零。通过传递性,将该值转换为整数的结果是实现定义的。
然而,更麻烦的是,reinterpret_cast 完成的映射无论如何都是实现定义的。因此,即使空指针值全部为零,实现也可以自由地产生任何它想要的结果。仅保证您在回传时会获得原始值。
话虽如此,您引用后的下一句话包括注释:
因此,尽管不需要特定的映射,但实际上您可以进行有根据的猜测。
† 假设
long
足够大。在 C++0x 中使用uintptr_t
,可以选择在
中定义。No,
i
is not necessarily any value. The result is implementation-defined.†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.
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:
So even though specific mappings are not required, pragmatically you can take an educated guess.
† Assuming
long
is large enough. In C++0x useuintptr_t
, optionally defined in<cstddef>
.我不明白为什么它不会。问题在于,所讨论的整数类型无法保存那么高的值,但如果它是空指针,则没有问题。
I don't see why it wouldn't. The issue is that the integer type in question wouldn't be able to hold values that high, but if it's a null pointer there's no problem.
你想要reinterpret_cast(pt),但是是的,那会起作用。 reinterpret_cast 与旧的 C 风格强制转换(长)相同,并假设您知道自己在做什么。
You want reinterpret_cast(pt) but yes, that will work. reinterpret_cast is the same as the old C style cast (long) and assumes you know what you are doing.
是的,运行时指向哪里并不重要;唯一重要的是指针的类型。 “指向数据对象或函数”仅意味着“常规”对象指针和函数指针(即指向对象代码的指针)都可以重新转换为数字类型。
我认为上面的代码在所有
已知常见平台上安全地将 0 存储到“i”。Yes, it does not matter where it points at runtime; the only thing that matters is the type of the pointer. "to a data object or to a function" just means that both "regular" object pointers as well as function pointers (i.e. pointers to object code) can be recast into numeric types.
I think the code you have above safely stores 0 to 'i' on all
knowncommon platforms.