Throwing an exception like 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 am trying to complete const correctness in my project and inadvertently created the above situation. Be that as it may, in Dev Studio, a catch DOES lock catches an exception, even though it is selected as const and is caught as non-const &.

Question - Should he ?:-)

+7
source share
2 answers

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

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

+9
source

I don’t know what the specification says, but it seems to me that in practice the exception is sent to the correct "catch" block using RTTI (for this some compiler with synthesized code must be executed) to which "const" does not matter.

0
source

All Articles