Boost logo

Boost :

From: Brey, Edward D (EdwardDBrey_at_[hidden])
Date: 2002-01-17 15:20:13


The potential for danger sure is there. It depends on the details. Allow
me to embellish your example:

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.

Note that this example raises the larger question of why the mechanism that
takes ownership of the pointer doesn't use a shared pointer in the first
place. Chances are it is because it has a legacy interface. Although such
interfaces are more error-prone, they do exist, and they are exactly what
release() is good at dealing with.

More modern interfaces take a smart pointer in the first place, so you never
need to use release() yourself. Consider shared_ptr. Its constructor can
take an auto_ptr, and it does the release for you once it has the pointer
safely tucked away.

-----Original Message-----
From: Douglas Gregor [mailto:gregod_at_[hidden]]
Sent: Thursday, 17 January 2002 2:12 PM
To: boost_at_[hidden]
Subject: Re: [boost] Re: shared_ptr: unsafe, or am I crazy?

On Thursday 17 January 2002 02:02 pm, you wrote:
> In regards to other comments on release(), in an ideal world it would
> not be necessary, but the real world contains other languages besides
> C++, and legacy APIs that are not optional. Providing some control
> over whether release() is exposed will only mean that the class can
> conditionally be made useless.

There appears to be a lot of animosity aimed at release(). Am I correct in
assuming that many here would prefer the removal of release() even from
std::auto_ptr? I've found release() to be quite useful if I need to allocate

several resources at once that won't be assigned to other smart pointers
immediately. For instance, I have several times written the following:

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

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

        Doug


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