static_cast vs dynamic_cast

自闭症网瘾萝莉.ら 提交于 2019-12-20 12:29:26

问题


Suppose I'm given a C++ library full of inheritance. I'm given a Base* in a function when I know that it is actually pointing to a Derived object and Derived inherits Base. But I don't know what kind of inheritance it is (public/protected/private). I also don't know if there is any virtual function in the hierarchy.

Given this situation, without looking into the source code/documentation of Base and Derived, which cast should I use? Or should I consult the code/documentation first to ensure about polymorphism?

Background

I am writing changeEvent function of QMainWindow in Qt 4.7. The changeEvent function takes QEvent* which I can cast to other type by knowing QEvent::type(). I was wondering if I should use static_cast or dynamic_cast.

Thanks.


回答1:


Use static_cast. If you know that your Base* points to a Derived, then use static_cast. dynamic_cast is useful for when it might point to a derived.




回答2:


When in doubt, you should prefer dynamic_cast. It might be slower, but you probably won't notice the difference anyway.

If you need speed, use the following snippet:

template <typename Derived, typename Base>
Derived safe_static_cast(Base b)
{
  assert((void*)dynamic_cast<Derived>(b) && "safe_static_cast failed!");
  return static_cast<Derived>(b);
}

Or something equivalent.

The idea is that in debug builds, it checks that it's indeed what you thought it would be, and it release builds... well everything has already been tested, hasn't it ?




回答3:


From MSDN -

In general you use static_cast when you want to convert numeric data types such as enums to ints or ints to floats, and you are certain of the data types involved in the conversion. static_cast conversions are not as safe as dynamic_cast conversions, because static_cast does no run-time type check, while dynamic_cast does. A dynamic_cast to an ambiguous pointer will fail, while a static_cast returns as if nothing were wrong; this can be dangerous. Although dynamic_cast conversions are safer, dynamic_cast only works on pointers or references, and the run-time type check is an overhead.

For more info, check out this link



来源:https://stackoverflow.com/questions/4648070/static-cast-vs-dynamic-cast

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!