Should I use reinterpret_cast when casting between int and class pointers?

Started by
11 comments, last by the_edd 15 years, 1 month ago
Quote:Original post by SymLinked
Quote:
When overriding a pointer as an integer, you'll need to be careful with 32/64 bit issues. Overriding a type as a type of different size can cause the binary writer to fail. In the case of hkpWorldObject, the alignment requirements of adjacent variables ensures that the object layout is still computed correctly for 64 bit machines.


Does it mean I'm safe?


If you have an integral type, X, such that sizeof(X) >= sizeof(SceneObject*), then the C++ standard guarantees that you can reinterpret_cast a SceneObject* to an X and back again without the final and original pointer values differing.

So if you use a static assertion to check the sizes, you can then reinterpret_cast to and fro safely. But pay attention to point 2 in NotAYakk's original post.

IMHO, it's best to avoid reinterpret_cast if you possibly can. But sometimes APIs force your hand.
Advertisement
Quote:Original post by NotAYakk
...


Thanks a lot man! I'm just not sure I want to head deep into this if the integer casting works, as the docs say it should (quoted further up) and all the examples point to this. I'm all for writing correct C++ code, but in this case I just want to move forward.

Quote:Original post by the_edd
If you have an integral type, X, such that sizeof(X) >= sizeof(SceneObject*), then the C++ standard guarantees that you can reinterpret_cast a SceneObject* to an X and back again without the final and original pointer values differing.


I was under the impression they took care of this:

Quote:
In the case of hkpWorldObject, the alignment requirements of adjacent variables ensures that the object layout is still computed correctly for 64 bit machines.


Guess I'll have to wait and see if it turns out to be an issue later.
Quote:Original post by SymLinked

I was under the impression they took care of this:

Quote:
In the case of hkpWorldObject, the alignment requirements of adjacent variables ensures that the object layout is still computed correctly for 64 bit machines.



In the larger quote that you posted earlier, they mention "overriding", which is a non-standard use of the term. It's also mentioned in the context of "binary writers", which again is something entirely outside of the C++ standard. It also mentions 32/64 bit alignment which again has little to do with the when/where/how reinterpret_cast works.

The C++ standard gives you all the guarantees you need, provided the integral type is large enough.

So the quote is largely irrelevant as far as the casting correctness issue is concerned.

This topic is closed to new replies.

Advertisement