c++ dynamic_cast error handling

后端 未结 5 1014
情话喂你
情话喂你 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:43

    I'd concur with the 'it depends' answer, and also add "Graceful degradation": just because a cast fails somewhere isn't enough reason to let the application fail (and the user lose his/her work, etc.). I'd recommend a combination of asserts and defensive programming:

    ptr = dynamic_cast(obj);
    ASSERT(ptr);
    if(ptr)
    {
       // do stuff
    }
    

提交回复
热议问题