Scott Meyers says:
C++ specifies that an object thrown as an exception is always copied and the copying is performed by the object’s copy constructor.
But in my code:
struct test
{
test() { cout << "constructor is called" << endl; }
test(const test&) { cout << "copy constructor is called" << endl; }
~test() { cout << "destructor is called" << endl; }
};
void fun()
{
throw test();
}
int main()
{
try {
fun();
}
catch (test& t1) { cout << "exception handler" << endl; }
}
I do not see the exception object’s copy constructor being called.
If I change the catch to receive the exception object by value then it is, but according to Meyers’s quote the exception object should have been copied even when it’s received by reference.
Why is the copy constructor is not called (even when exception handling is performed by reference)?
Meyers is correct that a copy is made, semantically:
However, copies can be elided by clever compilers and they are allowed to do so regardless of side-effects.