Proper way of casting pointer types

前端 未结 3 1958
忘掉有多难
忘掉有多难 2020-12-08 02:06

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

BYTE* pbNext = reinterpret_cast(
    VirtualAlloc(NULL, cbAll         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 02:54

    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.

提交回复
热议问题