c++ dynamic_cast error handling

后端 未结 5 1090
情话喂你
情话喂你 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条回答
  •  萌比男神i
    2021-02-07 01:29

    bad_cast is only thrown when casting references

    dynamic_cast< Derived & >(baseclass)
    

    NULL is returned when casting pointers

    dynamic_cast< Derived * >(&baseclass)
    

    So there's never a need to check both.

    Assert can be acceptable, but that greatly depends on the context, then again, that's true for pretty much every assert...

提交回复
热议问题