我应该在将 void* 转换为任何内容时使用 static_cast 还是 reinterpret_cast

static_castreinterpret_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.

相关文章