投放指针类型的正确方式

投放指针类型的正确方式

本文介绍了投放指针类型的正确方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑(以及):

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 c $ c> 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?

C ++标准对这种情况有一个偏好,建议改用一种方法

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

推荐答案

在这种情况下,任一转换都是可以接受的,所以你是正确的 static_cast 是可以的。

Either cast is acceptable in that situation, so you are correct that static_cast is okay.

当在两个指针类型之间转换时,可能是指针中保存的特定内存地址需要改变

When converting between two 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 avoid changing the pointer's stored value.

因为这个原因, $ c> static_cast ,除非您知道,需要 reinterpret_cast

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

这篇关于投放指针类型的正确方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 00:54