c++ dynamic_cast error handling

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

    It depends... ;-)

    If I really expected the dynamic_cast to give me something usable, for example if I and no one else added a polymorphic type to a container of pointers to a base class, then I would go with the reference cast and let the std::bad_cast kill my application - there wouldn't be much else to do, really.

    However, if I'm querying a polymorphic type for some capability exposed by an interface that it doesn't necessarily have to implement, then I'd go with the pointer cast and then a NULL wouldn't be an error (unless, of course, I expected the capability to really be there - but then I'd had gone for the reference cast in the first place...)

提交回复
热议问题