Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ exceptions throw by value catch by reference

In C++ when throwing object by value like: throw Exception(), this will create temp object, how can it be caught by reference? i know it works, but if it was a function return value or function call it would have failed without adding const to type, what is the difference ?

like image 325
shd Avatar asked Mar 08 '15 21:03

shd


1 Answers

First, when you write

throw Exception();

what's being thrown isn't actually the temporary object created by the prvalue expression Exception(). Conceptually, there's a separate object - the exception object - that's initialized from that temporary object, and it is the exception object that's actually thrown. (Compilers are allowed to elide the copy/move, though.)

Second, the language rules say that the exception object is always considered an lvalue. Hence it is allowed to bind to non-const lvalue references.

like image 71
T.C. Avatar answered Oct 20 '22 02:10

T.C.