Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-09-30 13:56:45


From: "Howard Hinnant" <hinnant_at_[hidden]>
> > shared_ptr's case is different, as its reset is allowed to throw:
> >
> > shared_ptr<X> px;
> > auto_ptr<X> px2;
> >
> > px = px2; // strong guarantee, px2 unchanged if reset throws
> > px.reset(px2.release()); // px2 NULL, object destroyed if reset throws
>
> Interesting example. A possible (but not necessarily better)
> alternative which keeps the interfaces decoupled is:
>
> px.reset(px2.get());
> px2.release();

No, this doesn't work. px.reset(X*) always takes ownership, even if an
exception is thrown:

px.reset(new X); // no leak, object deleted even if reset throws

and in our case above px2 will attempt to double-delete "its" pointer when
reset throws.

> I've just reviewed my own code and found that I've used this pattern
> several times when transferring ownership out of a local auto_ptr-like
> type.

So do I, but only in cases where the (implementation detail) function
doesn't take ownership when it throws, and such functions are usually a bad
idea, except at a certain library level where you live, and I visit
regularly. ;-)


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk