Should I use static_cast or reinterpret_cast when casting a void* to whatever

Use static_cast: it is the narrowest cast that exactly describes what conversion is made here.

There’s a misconception that using reinterpret_cast would be a better match because it means “completely ignore type safety and just cast from A to B”.

However, this doesn’t actually describe the effect of a reinterpret_cast. Rather, reinterpret_cast has a number of meanings, for all of which holds that “the mapping performed by reinterpret_cast is implementation-defined.” [5.2.10.3]

But in the particular case of casting from void* to T* the mapping is completely well-defined by the standard; namely, to assign a type to a typeless pointer without changing its address.

This is a reason to prefer static_cast.

Additionally, and arguably more important, is the fact that every use of reinterpret_cast is downright dangerous because it converts anything to anything else really (for pointers), while static_cast is much more restrictive, thus providing a better level of protection. This has already saved me from bugs where I accidentally tried to coerce one pointer type into another.

Leave a Comment