常量和重新解释强制转换是否在编译时发生? [英] Do constant and reinterpret cast happen at compile time?

查看:65
本文介绍了常量和重新解释强制转换是否在编译时发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到 static_cast 在编译时发生,而 dynamic_cast 在运行时发生,因此比<$慢c $ c> static_cast 。 dynamic_cast 可以返回空ptr(与指针一起使用时),否则会抛出错误的强制转换异常。我的问题是 reinterpret_cast const_cast 会在编译时或运行时发生吗?我认为解释转换在运行时发生,因为它的行为类似于 dynamic_cast ,指示转换是否成功。我对么 ? const_cast就是编译时间吗?

I have read that static_cast happens at compile time and dynamic_cast happens at run time thus are slower than static_cast. A dynamic_cast can either return a null ptr (when using with a pointer) or otherwise throw a bad cast exception. My question is what about reinterpret_cast and const_cast do they happen at compile time or run-time ? I would think that interpret cast happens at run-time since it behaves like dynamic_cast indicating if the cast was successful. Am i correct ? What about const_cast is that compile time ?

推荐答案

动态转换是唯一需要在运行时计算的。所有其他强制类型转换都是在编译时计算的。

The dynamic cast is the only that needs to be "calculated" in run-time. All other casts are calculated in compile-time.


  • static_cast 是基于您要投射FROM和TO的类型的固定函数。

  • const_cast 的机器代码实际上没有任何作用不仅允许将const值作为no-const传递,反之亦然。因此可以在编译时进行解析。

  • 对于 reinterpret_cast ,机器代码也可以在编译时进行解析。一旦它只不过是用谁在寻找指向类型A的指针,而正在寻找类型B的眼睛。

  • dynamic_cast 需要解析虚拟表,并根据FROM和TO类型调整虚拟方法的正确地址。这就是为什么它更复杂的原因!

  • The machine code for a static_cast is a fixed function based on the type you are casting FROM and TO.
  • The machine code for a const_cast is in fact nothing more than allow a const value to be passed as no-const or vice-versa. So it can be resolved in compile-time
  • For reinterpret_cast, the machine code can be resolved in compile-time as well. Once it's nothing more than "look to a pointer that is pointing to a type A with the eyes of who is looking for the type B".
  • The dynamic_cast needs to resolve virtual tables and adjust the correct addresses of virtual methods based on the type FROM and TO. That's why it's more complex!

这篇关于常量和重新解释强制转换是否在编译时发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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