Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

May I have a real life example where casting through void* works and reinterpret_cast doesn't?

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?

like image 491
sharptooth Avatar asked Jul 06 '11 10:07

sharptooth


People also ask

Should you ever use reinterpret_cast?

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.

What is the point of reinterpret_cast?

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.

What is the difference between static_cast and reinterpret_cast?

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.

What does casting to void do in C?

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.


1 Answers

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;
  }
}
like image 157
iammilind Avatar answered Oct 13 '22 01:10

iammilind