Search code examples
c++exceptionshared-ptr

C++: Throwing shared_ptr of derived and catching shared_ptr of base?


Ok, I've been told this problem: Why can you throw a pointer to a derived class and catch a pointer to its base... but you can't do that with shared_ptrs?

Example, this works:

class Base {};
class Derived : public Base {};
int main()
{   
    try 
    {   
        throw new Derived() ;
    }   
    catch( const Base2 * b ) 
    {   
        printf("Received a base" ) ; 
    }   

    return 0 ;
}

But this doesn't

int main()
{
    try
    {
        throw std::tr1::shared_ptr<Derived>( new Derived() ) ;
    }
    catch( const std::tr1::shared_ptr<Base> & b ) 
    {
        printf("Received a base" ) ;
    }
    return 0 ;
}

Any ideas?


Solution

  • You are correct that your second example doesn't work.

    The exception handler will only catch exceptions in very clearly defined ways. In particular, you cannot do an implicit conversion when catching. Only derived-to-base and pointer-to-derived to pointer-to-base conversions are applied. Since shared_ptr<derived> does not derive from shared_ptr<base>, and it is not a built-in pointer, it doesn't match.

    If you want to catch shared_ptr<base>, then convert to shared_ptr<base> before throwing.