When dynamic_cast will throw exception in case used with pointer?

前端 未结 2 881
独厮守ぢ
独厮守ぢ 2021-02-20 07:20

I am using dynamic_cast in my source to cast pointer as some thing like below,

Base *base = here storing the pointer;

Derived *derived = dynamic_cast

        
2条回答
  •  天命终不由人
    2021-02-20 08:06

    Any idea when the dynamic_cast can throw exception when used with pointer as I used in above source?

    In a well-defined program, it cannot. The standard does not allow it:

    [C++11: 5.2.7/9]: The value of a failed cast to pointer type is the null pointer value of the required result type. A failed cast to reference type throws std::bad_cast (18.7.2).

    However, if you pass dynamic_cast an invalid pointer, then you invoke undefined behaviour and anything may happen, including some implementation-defined C++ exception, or a runtime crash.

提交回复
热议问题