After a code review we had an issue with copy elison in try/catch block. After reading this page : cpp reference guide and particularly this paragraph :
When handling an exception, if the argument of the catch clause is of the same type (ignoring top-level cv-qualification) as the exception object thrown, the copy is omitted and the body of the catch clause accesses the exception object directly, as if caught by reference
I thought that copy elision for the argument in the catch will be performed automatically but one of the reviewer run a simple test showing that copy elision was not performed by the compiler :
#include <iostream>
class A
{
public:
A(){}
A(const A&){
std::cout<<"COPY CONSTRUCTOR\n";
}
};
int main()
{
try {
throw A{};
} catch(A a) {
throw a;
}
return 0;
}
When compiling with :
g++ a.cpp -std=c++11 -O3
I got the following output
COPY CONSTRUCTOR
COPY CONSTRUCTOR
terminate called after throwing an instance of 'A'
Aborted (core dumped)
I was expecting an output similar to (only one call of the copy constructor when the exception is thrown) :
COPY CONSTRUCTOR
terminate called after throwing an instance of 'A'
Aborted (core dumped)
The test has been run under Linux Ubuntu 16.04 with g++ version :
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
Is the test case invalid or my understanding of the copy elision wrong ? Thank you very much for your help