I recently learned that it is Undefined Behavior to reinterpret a POD as a different POD by reinterpret_cast
ing its address. So I'm just wondering what a potential use-case of reinterpret_cast
might be, if it can't be used for what its name suggests?
There are two situations in which I’ve used reinterpret_cast
:
To cast to and from char*
for the purpose of serialisation or when talking to a legacy API. In this case the cast from char*
to an object pointer is still strictly speaking UB (even though done very frequently). And you don’t actually need reinterpret_cast
here — you could use memcpy
instead, but the cast might under specific circumstances avoid a copy (but in situations where reinterpreting the bytes is valid in the first place, memcpy
usually doesn’t generate any redundant copies either, the compiler is smart enough for that).
To cast pointers from/to std::uintptr_t
to serialise them across a legacy API or to perform some non-pointer arithmetic on them. This is definitely an odd beast and doesn’t happen frequently (even in low-level code) but consider the situation where one wants to exploit the fact that pointers on a given platform don’t use the most significant bits, and these bits can thus be used to store some bit flags. Garbage collector implementations occasionally do this. The lower bits of a pointer can sometimes also be used, if the programmer knows that the pointer will always be aligned e.g. at an 8 byte boundary (so the lowest three bits must be 0).
But to be honest I can’t remember the last concrete, legitimate situation where I’ve actually used reinterpret_cast
. It’s definitely many years ago.
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