I'm designing an exception class, but ran into a case where a copy is being made which I don't want (plus, I don't understand why).
Consider the following cases:
// 1
Exception e;
throw e; // Copy: yes
//2
throw Exception(); // Copy: no
//3
throw Exception() << "extra info"; // Copy: yes
//4
Exception e;
e << "extra info"; // Copy: no
throw e; // Copy: yes
//5
Exception() << "test"; // Copy: no
//Where:
const CException& operator<<(const char* p)
{
m_extramsg.append( p );
return *this;
}
I can understand why in //1 a copy is made.. it is possible that e is defined before the try/catch and being used after the catch block.
I don't understand why case 3 needs a copy, and this is exactly how I want to use the Exception class. By the way, the copy is (afaik) being made at the return *this; in operator<<
Is there any way I can prevent this copy?
I've used a similar design in another project... had I known that it would make copies all the time I would not have done it...
P.S.
Yes, I catch by reference, also tried const reference but did not seem to matter.
P.S. 2
I don't want the 'const char*' to be an argument to the constructor - I want to basically use the class as cout, with (semi) arbitrary data.. like status codes etc. e.g.:
HRESULT status = Some_function();
if( something something )
throw Exception() << "XX failed with code: " << status << "\n";