Proper way of casting pointer types

Mr.C64 picture Mr.C64 · Mar 22, 2013 · Viewed 66.5k times · Source

Considering the following code (and the fact that VirtualAlloc() returns a void*):

BYTE* pbNext = reinterpret_cast<BYTE*>(
    VirtualAlloc(NULL, cbAlloc, MEM_COMMIT, PAGE_READWRITE));

why is reinterpret_cast chosen instead of static_cast?

I used to think that reinterpret_cast is OK for e.g. casting pointers to and from integer types (like e.g. DWORD_PTR), but to cast from a void* to a BYTE*, isn't static_cast OK?

Are there any (subtle?) differences in this particular case, or are they just both valid pointer casts?

Does the C++ standard have a preference for this case, suggesting a way instead of the other?

Answer

Drew Dormann picture Drew Dormann · Mar 22, 2013

For convertible pointers to fundamental types both casts have the same meaning; so you are correct that static_cast is okay.

When converting between some pointer types, it's possible that the specific memory address held in the pointer needs to change.

That's where the two casts differ. static_cast will make the appropriate adjustment. reinterpret_cast will not.

For that reason, it's a good general rule to static_cast between pointer types unless you know that reinterpret_cast is desired.