dynamic_cast not throwing exceptions as expected

后端 未结 2 1815
-上瘾入骨i
-上瘾入骨i 2021-01-26 00:55

Based on this answer...

Finding the type of an object in C++

...I wrote this code:

        static TVALUE getUpperBou         


        
相关标签:
2条回答
  • 2021-01-26 01:46

    You are casting to a pointer. bad_cast is only generated when casting to a reference.

    You can just check for nullptr if casting to a reference isn't desirable.

    0 讨论(0)
  • 2021-01-26 01:55

    dynamic_cast only throws exceptions on failure if its template argument is a reference type.
    When it's a pointer type, dynamic_cast instead evaluates to NULL on failure.

    This is made very clear in the preferred language reference, for which you could simply have Googled:

    5c) Otherwise, the runtime check fails. If the dynamic_cast is used on pointers, the null pointer value of type _new_type_ is returned. If it was used on references, the exception std::bad_cast is thrown.

    I also don't understand why you expect an int to be thrown, rather than something that derives std::exception. Perhaps you were hoping that return in a try block jumps to the matching catch block? It doesn't.

    0 讨论(0)
提交回复
热议问题