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?
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 has a number of meanings, for all of which holds that “the mapping performed by
reinterpret_cast is implementation-defined.” [184.108.40.206]
But in the particular case of casting from
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
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.