简体   繁体   中英

Throw bad_cast when converting pointers with dynamic_cast?

dynamic_cast throws bad_cast exception if you cast a reference but as I know in the standard pointers are considered as references, ie a pointer is a type of a reference.
So should I get bad_cast when casting pointers?

This question arose from the try-catch block from this page . Is this try-catch block inappropriate?

No with pointers in case of a bad cast, dynamic_cast will return a null .
Also, dynamic_cast works only on Polymorphic classes, So if you are talking about built in data types(from the link in your question) then static_cast is what you should be using.

And btw, References are NOT pointers.

Regarding the original question "So should I get bad_cast when casting pointers?", No.

That's why you can see constructions like

if( T* pT = dynamic_cast<T*>( p ) ) ...  // use pT in if body

Regarding the new question "Is this try-catch block inappropriate?", no, it is a try - catch block to catch allocation errors; it's not related to the dynamic_cast as such.

Cheers & hth.,

Since dynamic_cast<T*> does not throw exceptions, one of the try-catch blocks are completely unnecessary.

However you can easily define your own cast function that does indeed throw exception for pointers. That is what I am doing in my own code (simplified code, and mind you I use garbage collection so I can throw pointers without consequence):

template <class Class, class Object>
inline Class* cast (Object* obj)
{
    Class* result = dynamic_cast<Class*>(obj);
    if( obj != null and result == null ){
        throw new ClassCastException(); //  unusual, throw bad_cast if you prefer
    }
    return result;
}

template <class Class, class Object>
inline const Class* cast (const Object* obj)
{
    const Class* result = dynamic_cast<const Class*>(obj);
    if( obj != null and result == null ){
        throw new ClassCastException(); //  unusual, throw bad_cast if you prefer
    }
    return result;
}

On a side note, I also use it as a syntactic sugar for static_cast, but this is only possible because I do not use it to dynamic_cast references and const references:

template <class Class, class Object>
inline Class cast (const Object& obj)
{
    return static_cast<Class>(obj);
}

I'd say you are better off implementing your own casting function that is coherent in terms of exception handling and do precisely what you want and expect. I did and never looked back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM