Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? :-)

like image 479
Grimm The Opiner Avatar asked Jan 19 '12 14:01

Grimm The Opiner


1 Answers

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.

like image 62
CB Bailey Avatar answered Oct 29 '22 18:10

CB Bailey