我应该使用static_cast或reinterpret_cast当投射一个void *任何东西 [英] Should I use static_cast or reinterpret_cast when casting a void* to whatever

查看:89
本文介绍了我应该使用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.

这篇关于我应该使用static_cast或reinterpret_cast当投射一个void *任何东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆