Proper way of casting pointer types(转换指针类型的正确方法)
问题描述
考虑到以下代码(和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.
这篇关于转换指针类型的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:转换指针类型的正确方法
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
