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";

Recommended Answers

All 2 Replies

>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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.