我应该使用static_cast或reinterpret_cast当投射一个void *任何东西
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?
您应该使用
reinterpret_cast
,因为它能更好地描述您正在做什么(完全忽略类型安全)
You should use a
reinterpret_cast
, because that describes better what you're doing (completely ignoring type safety)
这实际上不是描述 reinterpret_cast
的效果。相反, reinterpret_cast
有许多含义,对于所有这些都认为 reinterpret_cast
定义。[5.2.10.3]
This does actually not 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]
但是,这不是在这种特殊情况下会发生什么,
However, this is not what happens in this particular case, where the mapping is well-defined by the standard, namely assigning 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.