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


Question

Both static_cast and reinterpret_cast seem to work fine for casting void* to another pointer type. Is there a good reason to favor one over the other?

1
175
4/10/2010 4:06:18 PM

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.

125
10/18/2016 12:54:03 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon