I have a const pointer to a pointer to a Fred and I don’t understand why a static_cast isn’t sufficient.
typedef struct {
int n;
} Fred;
Fred *pFred;
Fred **const ppFred = &pFred;
void **const ppVoid = static_cast<void ** const>(ppFred);
Please could someone explain why a reinterpret_cast is needed to convert a pointer to Fred*to a pointer to void* but static_cast is fine to convert pointer to Fred to a pointer to void.
There’s no requirement that a
Fred*and avoid*have the same sizeand representation. (I’ve worked on machines where they didn’t,
although that was before my C++ days.) When you convert
Fred*tovoid*, you get a new pointer, with a possibly different size andrepresentation, but there is no information about the size and
representation of the object the
void*points to. You know that it isunknown, and the only way to use this
void*is to cast it back to aFred*(modulo things like cv-qualifiers). When you convertFred**to
void**, you’re converting from a pointer to a concrete type (apointer to a
Fred*) to a pointer to another concrete type (a pointerto a
void*). And since there’s no guarantee that these two concretetypes have the same size and representation, the conversion requires a
reinterpret_cast.voidis a special, non-concrete type, so you canstatic_casta pointer to any type to and from a pointer tovoid.void*is just another concrete pointer type, so casting to and frompointers to it follows the usual rules (and requires a
reinterpret_cast).In many ways, the situation is very much like
intanddouble, wherevoid*plays the role ofint(say), andFred*the role ofdouble.There’s no problem
static_casting betweenintanddouble, butcasts between
int*anddouble*requirereinterpret_cast.