int i = 1000;
void *p = &i;
int *x = static_cast<int*>(p);
int *y = reinterpret_cast<int*>(p);
which cast should be used to convert from void*
to int*
and why?
static_cast
provided that you know (by design of your program) that the thing pointed to really is an int
.
static_cast is designed to reverse any implicit conversion. You converted to void*
implicitly, therefore you can (and should) convert back with static_cast
if you know that you really are just reversing an earlier conversion.
With that assumption, nothing is being reinterpreted - void
is an incomplete type, meaning that it has no values, so at no point are you interpreting either a stored int value "as void" or a stored "void value" as int. void*
is just an ugly way of saying, "I don't know the type, but I'm going to pass the pointer on to someone else who does".
reinterpret_cast
if you've omitted details that mean you might actually be reading memory using a type other than the type is was written with, and be aware that your code will have limited portability.
By the way, there are not very many good reasons for using a void*
pointer in this way in C++. C-style callback interfaces can often be replaced with either a template function (for anything that resembles the standard function qsort
) or a virtual interface (for anything that resembles a registered listener). If your C++ code is using some C API then of course you don't have much choice.
In current C++, you can't use reinterpret_cast
like in that code. For a conversion of void*
to int*
you can only use static_cast
(or the equivalent C-style cast).
For a conversion between different function type pointers or between different object type pointers you need to use reinterpret_cast
.
In C++0x, reinterpret_cast<int*>(p)
will be equivalent to static_cast<int*>(p)
. It's probably incorporated in one of the next WPs.
It's a misconception that reinterpret_cast<T*>(p)
would interpret the bits of p
as if they were representing a T*
. In that case it will read the value of p
using p
's type, and that value is then converted to a T*
. An actual type-pun that directly reads the bits of p
using the representation of type T*
only happens when you cast to a reference type, as in reinterpret_cast<T*&>(p)
.
As far as I know, all current compilers allow to reinterpret_cast
from void*
and behave equivalent to the corresponding static_cast
, even though it is not allowed in current C++03. The amount of code broken when it's rejected will be no fun, so there is no motivation for them to forbid it.
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