Can I convert a null pointer of int to a long type by reinterpret_cast

。_饼干妹妹 提交于 2021-01-27 02:54:08

问题


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?


回答1:


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:

[ 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.


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




回答2:


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.




回答3:


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.




回答4:


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 known common platforms.



来源:https://stackoverflow.com/questions/5640748/can-i-convert-a-null-pointer-of-int-to-a-long-type-by-reinterpret-cast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!