I’m reading a book and I found that reinterpret_cast should not be used directly, but rather casting to void* in combination with static_cast:
T1 * p1=...
void *pv=p1;
T2 * p2= static_cast<T2*>(pv);
Instead of:
T1 * p1=...
T2 * p2= reinterpret_cast<T2*>(p1);
However, I can’t find an explanation why is this better than the direct cast. I would very appreciate if someone can give me an explanation or point me to the answer.
Thanks in advance
p.s. I know what is reinterpret_cast used for, but I never saw that is used in this way
For types for which such cast is permitted (e.g. if
T1is a POD-type andT2isunsigned char), the approach withstatic_castis well-defined by the Standard.On the other hand,
reinterpret_castis entirely implementation-defined – the only guarantee that you get for it is that you can cast a pointer type to any other pointer type and then back, and you’ll get the original value; and also, you can cast a pointer type to an integral type large enough to hold a pointer value (which varies depending on implementation, and needs not exist at all), and then cast it back, and you’ll get the original value.To be more specific, I’ll just quote the relevant parts of the Standard, highlighting important parts:
5.2.10[expr.reinterpret.cast]:
So something like this:
is effectively unspecified.
Explaining why
static_castworks is a bit more tricky. Here’s the above code rewritten to usestatic_castwhich I believe is guaranteed to always work as intended by the Standard:Again, let me quote the sections of the Standard that, together, lead me to conclude that the above should be portable:
3.9[basic.types]:
3.9.2[basic.compound]:
3.10[basic.lval]:
4.10[conv.ptr]:
5.2.9[expr.static.cast]:
[EDIT] On the other hand, we have this gem:
9.2[class.mem]/17:
which seems to imply that
reinterpret_castbetween pointers somehow implies “same address”. Go figure.