Boost logo

Boost :

From: Gary Powell (powellg_at_[hidden])
Date: 2002-01-17 16:55:01


>>
std::auto_ptr<type1> p1 = new type1(...);
std::auto_ptr<type2> p2 = new type2(...);
std::auto_ptr<type3> p3 = new type3(...);

// do lots of frightening exception-throwing stuff
transfer_to_new_owner(p1);
transfer_to_new_owner(p2);
transfer_to_new_owner(p3);

// danger of exceptions is gone, and the allocated pointers have
// safely been stored in other places .
p1.release();
p2.release();
p3.release();

If, say, transfer_to_new_owner(p2) throws, you're in big trouble. This
brings to light an example of how auto_ptr is meant to be used with legacy
interfaces:

std::auto_ptr<type1> p1 = new type1(...);
// Use p1
transfer_to_new_owner(p1.release());

Now you're safe, so long as transfer_to_new_owner is doing its job.
<<
Shouldn't this be:
std::auto_ptr<type1> p1 = new type1(...);
// Use p1
transfer_to_new_owner(p1.get());
p1.release();

If transfer_to_new_owner(type1 *) throws before it actually takes over
ownership of p1, your example leaks p1.
Of course if it throws after it takes ownership, you're still in big
trouble. Generally things that take ownership that may throw allocate the
new thing to put the pointer in, then take over control. (But not always!)

And yes, in modern c++ transfer_to_new_owner should either take an auto_ptr,
or a smart_ptr.

 Yours,
 -gary-


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