I hear that reinterpret_cast
is implementation defined, but I don't know what this really means. Can you provide an example of how it can go wrong, and it goes wrong, is it better to use C-Style cast?
I hear that reinterpret_cast
is implementation defined, but I don't know what this really means. Can you provide an example of how it can go wrong, and it goes wrong, is it better to use C-Style cast?
The C-style cast isn't better.
It simply tries the various C++-style casts in order, until it finds one that works. That means that when it acts like a reinterpret_cast
, it has the exact same problems as a reinterpret_cast
. But in addition, it has these problems:
reinterpret_cast
, a const_cast
or a static_cast
, and those do very different things)reinterpret_cast
is easy to find, which is good, because casts are ugly and should be paid attention to when used. Conversely, a C-style cast (as in (int)42.0
) is much harder to find reliably by searchingTo answer the other part of your question, yes, reinterpret_cast
is implementation-defined. This means that when you use it to convert from, say, an int*
to a float*
, then you have no guarantee that the resulting pointer will point to the same address. That part is implementation-defined. But if you take the resulting float*
and reinterpret_cast
it back into an int*
, then you will get the original pointer. That part is guaranteed.
But again, remember that this is true whether you use reinterpret_cast
or a C-style cast:
int i;
int* p0 = &i;
float* p1 = (float*)p0; // implementation-defined result
float* p2 = reinterpret_cast<float*>(p0); // implementation-defined result
int* p3 = (int*)p1; // guaranteed that p3 == p0
int* p4 = (int*)p2; // guaranteed that p4 == p0
int* p5 = reinterpret_cast<int*>(p1); // guaranteed that p5 == p0
int* p6 = reinterpret_cast<int*>(p2); // guaranteed that p6 == p0