C ++ throw by value catch exceptions by reference

In C ++, when throwing an object by value, for example: throw Exception (), this will create a temporary object, how can I catch it by reference? I know this works, but if it were a function of a return value or a function call, it would fail without adding a constant to the type, what's the difference?

+7
c ++ exception-handling
source share
1 answer

First when you write

throw Exception(); 

what is being thrown is not really a temporary object created by the prvalue Exception() expression. Conceptually, there is a separate object - an exception object - that is initialized from this temporary object, and this is actually an exception object. (Compilers are allowed to delete copy / move.)

Secondly, language rules say that an exception object is always considered an lvalue. Therefore, it is allowed to bind to non-constant lvalue references.

+6
source share

All Articles