Re: std::auto_ptr as exception object
On Apr 28, 9:19 am, j.l.ols...@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?
Is catching by reference kosher?
It's the usual practice, since it takes polymorphism into
account.
Are there other problems with throwing auto_ptrs?
Well, the copy constructor takes a non-const reference, so you
cannot copy a temporary. (In other words, your example
shouldn't compile---although I couldn't find a compiler which
rejects it.)
The usual practice would be to throw by value, and catch by
const reference:
try {
throw 10 ;
} catch ( int const& err ) {
throw ;
}
(Of course, you almost never throw int's. In practice, you'd
throw some specific class derived from std::exception.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34