简体   繁体   中英

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. Here is a first draft version of the note:

“Prefer static_cast over dynamic_cast . Use dynamic_cast only if dynamic (=runtime) class hierarchy navigation is unavoidable.“

My thoughts on this note are: The advantage of the compiletime checks of static_cast should be used. 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

Is my note regarding c++ coding style correct?

Is static_cast to be prefered over dynamic_cast in c++?

Certainly. If static cast is an option, then it is a better option than dynamic cast. In other words, dynamic cast should only be used if static cast is not an option. Don't take this too far though. Implementing your own parallel RTTI just so you can avoid dynamic cast would be misguided.

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.

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. In general, static cast is less safe than dynamic cast. It is preferred because it has less runtime overhead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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