0

I'm using reinterpret_cast something like this:

void RunThread (void *myself)
{
   (reinterpret_cast<MyClass*>(myself))->Method();
}

Inside Method, most of my member variables (all Handles) are null. Could this be because of reinterpret_cast since I know it does not guarantee me the same addresses? Like static_cast would. I know we should be using static_case in this instance, but this issue has got me interested now.

Science_Fiction
  • 3,403
  • 23
  • 27

1 Answers1

3

No. reinterpret_cast doesn't perform any operations on source pointer, just treats its value as another pointer (or integral) type. It could give you wrong result only in case when memory pointed bymyself does not contain MyClass (or binary compatible) object.

Rost
  • 8,779
  • 28
  • 50
  • http://stackoverflow.com/questions/573294/when-to-use-reinterpret-cast. When the top voted answer says: static_casting a pointer to and from void* preserves the address. What does he mean? – Science_Fiction Aug 20 '12 at 10:49
  • @Science_Fiction He means that `static_cast` doesn't change the *value* of pointer, but its *type* only. Let you have `MyClass* p = new MyClass();`. It will point to some allocated memory with some distinct address, say `0x100000`. `void* pv = static_cast(p);` will guarantee that 'pv' will have same value `0x100000`. Strictly formally `reinterpret_cast` doesn't guarantee so, but I don't know the platform where it works different way. – Rost Aug 20 '12 at 11:13
  • @Science_Fiction Of course, if you need only `MyClass*` -> `void*` and back casts you shal prefer `static_cast`, not `reinterpret_cast`. – Rost Aug 20 '12 at 11:17