Avoiding dynamic_cast/RTTI

前端 未结 6 790
执笔经年
执笔经年 2020-12-16 23:13

I was recently working on a piece of C++ code for a side project (the cpp-markdown library, for the curious), and ran into a coding question that I\'d like some opinions on.

6条回答
  •  孤街浪徒
    2020-12-17 00:07

    Why do you want to avoid using dynamic_cast? Is it causing an unacceptable bottle neck on your application? If not it might not be worth doing anything to the code right now.

    If you are ok with trading some amount of safety for a bit of speed in your particular situation you should be fine doing a static_cast; however, this is cementing your assumption that you know the type of the object and there is no chance of the cast being bad. If your assumption becomes wrong later, you could end up with some mysterious crash bugs in your code. Going back to my original question, are you really sure the trade off is worth it here?

    As for the options you listed: The first doesn't really sound like a solution as much as a last minute hack I would expect to see thrown in when someone was writing code at 3 AM. Functionality trickling its way towards the base of the class hierarchy is one of the most common anti-patterns hit by people new to OOP. Don't do it.

    For the second option you listed any option like that are really just reimplementing dynamic_cast - if you are on a platform with only crap compilers available (I've heard stories about the Gamecube's compiler taking up a quarter of the system's available RAM with RTTI info) this might worthwhile, but more than likely you are just wasting your time. Are you really sure this is something worth concerning yourself about?

提交回复
热议问题