c++ dynamic_cast error handling

后端 未结 5 1016
情话喂你
情话喂你 2021-02-07 01:05

Is there any good practice related to dynamic_cast error handling (except not using it when you don\'t have to)? I\'m wondering how should I go about NULL and bad_cast it can th

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-07 01:40

    Yes and no.

    boost::polymorphic_downcast<> is surely a good option to handle errors of dynamic_cast<> during the debug phase. However it's worth to mention that polymorphic_downcast<> should be used only when it's possible to predict the polymorphic type passed at compile time, otherwise the dynamic_cast<> should be used in place of it.

    However a sequence of:

    if (T1* t1 = dynamic_cast(o)) 
    { }
    if (T2* t2 = dynamic_cast(o)) 
    { }
    if (T3* t3 = dynamic_cast(o)) 
    { }
    

    denotes a very bad design that should be settle by polymorphism and virtual functions.

提交回复
热议问题