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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With