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

throw Exception(); // Copy: no

throw Exception() << "extra info"; // Copy: yes

Exception e;
e << "extra info"; // Copy: no
throw e; // Copy: yes

Exception() << "test"; // Copy: no

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...

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";
7 Years
Discussion Span
Last Post by thelamb

>Is there any way I can prevent this copy?
No, not really. In calling operator<<, you've bound the temporary object to a reference, which basically invalidates it for further copy elimination.

>had I known that it would make copies all the time I would not have done it...
It's best to assume that at least one copy of an exception object will be made when throwing.


Hmm ok that's annoying, but I suppose it makes sense.
I hoped that I overlooked something that would eliminate the copy, too bad ;)

Thanks Narue

Edited by thelamb: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.