Grimm The Opiner
Grimm The Opiner

Reputation: 1806

Throwing an exception as const&

Take the following code;

void DoThrow( const std::exception& e )
{
    throw e;
}

int main( int nArgs, char* args[] )
{
    std::exception e;
    try
    {
        DoThrow( e );
    }
    catch( std::exception& e )
    {
        // const exception ref is caught
    }


    return 0;
}

I'm trying to retrofit const correctness in my project and inadvertently created the above situation. As it stands, in Dev Studio the catch block DOES catch the exception, despite the fact that it is thrown as a const & but caught as a non-const &.

Question - Should it? :-)

Upvotes: 7

Views: 490

Answers (2)

CB Bailey
CB Bailey

Reputation: 792497

throw takes an expression and creates via copy-initialization an exception object based on the static type of that expression. The exception object is not a const object.

The catch statement initializes a reference to the exception object, not the object (if any) referred to by the throw expression.

Upvotes: 9

araqnid
araqnid

Reputation: 133662

I don't know about what the specification says, but it seems to me that in practice, an exception is dispatched to the correct "catch" block using RTTI (some compiler synthesised code must do this), to which "const" is irrelevant.

Upvotes: 0

Related Questions