First of all, this is not a duplicate of Why do we have reinterpret_cast in C++ when two chained static_cast can do it's job?.
I know situations where we cannot use even two chained static_cast
to achieve that, what reinterpret_cast
does. But is there any situation where I should prefer a two chained static_cast
over a simple and more readable reinterpret_cast
?
static_cast only allows conversions like int to float or base class pointer to derived class pointer. reinterpret_cast allows anything, that's usually a dangerous thing and normally reinterpret_cast is rarely used, tipically to convert pointers to/from integers or to allow some kind of low level memory manipulation.
Purpose for using reinterpret_cast It is used when we want to work with bits. If we use this type of cast then it becomes a non-portable product. So, it is suggested not to use this concept unless required. It is only used to typecast any pointer to its original type.
In short: static_cast<>() gives you a compile time checking ability, C-Style cast doesn't. static_cast<>() is more readable and can be spotted easily anywhere inside a C++ source code, C_Style cast is'nt. Intentions are conveyed much better using C++ casts.
static_cast − This is used for the normal/ordinary type conversion. This is also the cast responsible for implicit type coersion and can also be called explicitly. You should use it in cases like converting float to int, char to int, etc. dynamic_cast −This cast is used for handling polymorphism.
reinterpret_cast
should be a huge flashing symbol that says THIS LOOKS CRAZY BUT I KNOW WHAT I'M DOING. Don't use it just out of laziness.
reinterpret_cast
means "treat these bits as ..." Chained static casts are not the same because they may modify their targets according to the inheritence lattice.
struct A {
int x;
};
struct B {
int y;
};
struct C : A, B {
int z;
};
C c;
A * a = &c;
int main () {
assert (reinterpret_cast <B *> (a) != static_cast <B *> (static_cast <C *> (a)));
}
If you are not 100% sure that a
points to a b
, use dynamic_cast
which will search for the above solution (albeit with a runtime cost). Bear in mind that this may return NULL or throw on failure.
I'm trying to think of times when I've actually used reinterpret_cast
, there are really only two:
const char *
to traverse itif(*reinterpret_cast<uint32_t*>(array_of_4_bytes_A) < *reinterpret_cast<uint32_t*>(array_of_4_bytes_B)
or somesuch. Lines like this invite scrutiny and demand comments.Otherwise if you have a A*
which is really a B*
then you probably want a union.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With