HeretoLearn HeretoLearn - 1 year ago 75
C++ Question

When to use reinterpret_cast?

I am little confused with the applicability of

. From what I have read the general rules are to use static cast when the types can be interpreted at compile time hence the word
. This is the cast the C++ compiler uses internally for implicit casts also.
are applicable in two scenarios, convert integer types to pointer types and vice versa or to convert one pointer type to another. The general idea I get is this is unportable and should be avoided. Where I am a little confused is one usage which I need, I am calling C++ from C and the C code needs to hold on to the C++ object so basically it holds a
. What cast should be used to convert between the
void *
and the Class type?

I have seen usage of both

? Though from what I have been reading it appears
is better as the cast can happen at compile time? Though it says to use
to convert from one pointer type to another?

Answer Source

The C++ standard guarantees the following:

static_casting a pointer to and from void* preserves the address. That is, in the following, a, b and c all point to the same address:

int* a = new int();
void* b = static_cast<void*>(a);
int* c = static_cast<int*>(b);

reinterpret_cast only guarantees that if you cast a pointer to a different type, and then reinterpret_cast it back to the original type, you get the original value. So in the following:

int* a = new int();
void* b = reinterpret_cast<void*>(a);
int* c = reinterpret_cast<int*>(b);

a and c contain the same value, but the value of b is unspecified. (in practice it will typically contain the same address as a and c, but that's not specified in the standard, and it may not be true on machines with more complex memory systems.)

For casting to and from void*, static_cast should be preferred.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download