Should I use static_cast or reinterpret_cast when casting a void* to whatever(我应该在将 void* 转换为任何内容时使用 static_cast 还是 reinterpret_cast)
问题描述
static_cast 和 reinterpret_cast 似乎都可以很好地将 void* 转换为另一种指针类型.是否有充分的理由偏爱其中一个?
Both static_cast and reinterpret_cast seem to work fine for casting void* to another pointer type. Is there a good reason to favor one over the other?
推荐答案
使用 static_cast:它是最窄的强制转换,准确地描述了此处进行的转换.
Use static_cast: it is the narrowest cast that exactly describes what conversion is made here.
有一种误解,认为使用 reinterpret_cast 会更好,因为它意味着完全忽略类型安全,只是从 A 转换到 B".
There’s a misconception that using reinterpret_cast would be a better match because it means "completely ignore type safety and just cast from A to B".
然而,这实际上并没有描述 reinterpret_cast 的效果.相反,reinterpret_cast 有多种含义,因为所有这些含义都认为reinterpret_cast 执行的映射是实现定义的."[5.2.10.3]
However, this doesn’t actually describe the effect of a reinterpret_cast. Rather, reinterpret_cast has a number of meanings, for all of which holds that "the mapping performed by reinterpret_cast is implementation-defined." [5.2.10.3]
但是在从 void* 转换到 T* 的特殊情况下,映射完全由标准定义;即,在不改变其地址的情况下为无类型指针分配类型.
But in the particular case of casting from void* to T* the mapping is completely well-defined by the standard; namely, to assign a type to a typeless pointer without changing its address.
这是选择 static_cast 的原因.
此外,可以说更重要的是,reinterpret_cast 的每次使用都是彻头彻尾的危险,因为它实际上将任何东西转换为其他任何东西(对于指针),而 static_cast限制更多,从而提供更好的保护水平.这已经让我避免了错误,因为我不小心试图将一种指针类型强制转换为另一种类型.
Additionally, and arguably more important, is the fact that every use of reinterpret_cast is downright dangerous because it converts anything to anything else really (for pointers), while static_cast is much more restrictive, thus providing a better level of protection. This has already saved me from bugs where I accidentally tried to coerce one pointer type into another.
这篇关于我应该在将 void* 转换为任何内容时使用 static_cast 还是 reinterpret_cast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我应该在将 void* 转换为任何内容时使用 static_c
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
