转换指针类型的正确方法

考虑到以下代码(和VirtualAlloc() 返回一个 void*):

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

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

为什么选择 reinterpret_cast 而不是 static_cast?

why is reinterpret_cast chosen instead of static_cast?

我曾经认为 reinterpret_cast 可以用于例如将指针转换为整数类型(例如 DWORD_PTR),但是从 void* 转换为 BYTE*,不是 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?

C++ 标准是否对这种情况有偏好,建议一种方法而不是另一种方法?

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

推荐答案

对于可转换的指向基本类型的指针,两个强制转换具有相同的含义;所以你说 static_cast 没问题是正确的.

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.

这就是两个演员表不同的地方.static_cast 会做适当的调整.reinterpret_cast 不会.

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

因此,除非您知道需要reinterpret_cast,否则在指针类型之间static_cast 是一个很好的一般规则.

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

相关文章