There's a set of questions regarding cross-casts (cast from T1*
to unrelated T2*
), for example this and this. The answer usually goes like this: reinterpret_cast
is implementation defined and conversion to void*
followed by static_cast
is well-defined. Yet I haven't see any real examples of what can go wrong when reinterpret_cast
is used.
What are real-life examples where casting through void*
works and reinterpret_cast
doesn't?
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.
The reinterpret_cast allows the pointer to be treated as an integral type. The result is then bit-shifted and XORed with itself to produce a unique index (unique to a high degree of probability). The index is then truncated by a standard C-style cast to the return type of the function.
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.
Casting to void is used to suppress compiler warnings. The Standard says in §5.2. 9/4 says, Any expression can be explicitly converted to type “cv void.” The expression value is discarded.
real-life examples where casting through void* works and reinterpret_cast doesn't
If I interpret this sentence as, casting through void*
works to help me avoid undefined behavior and reinterpret_cast
doesn't then following is an example.
reinterpret_cast<TYPE*&>
(pointer reference) may break strict aliasing rule (it happens for g++ at least) and leads you to an undefined behavior. Demo.
However, static_cast<void*&>
will result in compiler error and save you from such undefined behavior. Demo.
I have seen such use in a smart pointer:
template<class TYPE>
struct SmartPointer
{
void *p;
TYPE& operator ++ ()
{
(reinterpret_cast<TYPE*&>(p))++; // breaking strict aliasing rule
return *this;
}
}
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