简体   繁体   English

在 c++ 中,static_cast 是否比 dynamic_cast 更受欢迎?

[英]Is static_cast to be prefered over dynamic_cast in c++?

I am thinking about the potential of a company internal note regarding our internal c++ code style guide.我正在考虑关于我们内部 c++ 代码样式指南的公司内部说明的潜力。 Here is a first draft version of the note:这是该说明的初稿:

“Prefer static_cast over dynamic_cast . “更喜欢static_cast而不是dynamic_cast Use dynamic_cast only if dynamic (=runtime) class hierarchy navigation is unavoidable.“仅当动态(=运行时)class 层次结构导航不可避免时才使用dynamic_cast 。“

My thoughts on this note are: The advantage of the compiletime checks of static_cast should be used.我对这篇笔记的想法是:应该使用static_cast的编译时检查的优势。 In my opinion it is a good idea to relocate potential errors from runtime to compiletime.在我看来,将潜在错误从运行时重新定位到编译时是一个好主意。 The second sentence of the note is copied and modified from here:注释的第二句是从这里复制和修改的:

CppCoreGuidelines CppCore指南

Is my note regarding c++ coding style correct?我关于 c++ 编码风格的注释是否正确?

Is static_cast to be prefered over dynamic_cast in c++?在 c++ 中,static_cast 是否比 dynamic_cast 更受欢迎?

Certainly.当然。 If static cast is an option, then it is a better option than dynamic cast.如果 static 演员表是一个选项,那么它是比动态演员表更好的选择。 In other words, dynamic cast should only be used if static cast is not an option.换句话说,只有在 static 转换不是一个选项时才应该使用动态转换。 Don't take this too far though.不过不要走得太远。 Implementing your own parallel RTTI just so you can avoid dynamic cast would be misguided.实现自己的并行 RTTI 只是为了避免动态转换会被误导。

Furthermore, when static cast is not an option, I would recommend at least considering other design choices such as introducing a virtual function instead of using dynamic cast.此外,当 static 转换不是一个选项时,我建议至少考虑其他设计选择,例如引入虚拟 function 而不是使用动态转换。

In my opinion it is a good idea to relocate potential errors from runtime to compiletime.在我看来,将潜在错误从运行时重新定位到编译时是一个好主意。

I cannot think of a runtime error that would be relocated to compiletime by switching dynamic cast to static cast.我想不出通过将动态转换切换到 static 转换来重新定位到编译时的运行时错误。 In general, static cast is less safe than dynamic cast.通常,static 投射不如动态投射安全。 It is preferred because it has less runtime overhead.它是首选,因为它具有较少的运行时开销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM