Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2001-04-06 07:29:11


From: "David Abrahams" <abrahams_at_[hidden]>

> From: "Peter Dimov" <pdimov_at_[hidden]>
>
> > > my_any_pair(shared_ptr<string>(auto_ptr<string>(new string("text") ),
> > > auto_ptr<string>(new string("text2") );
> > >
> > > where I don't really want to have default construction, and then do
the
> > > assignment the "safe" way.
> >
> > Again, you don't need the auto_ptr. shared_ptr<string>(new
string("text"))
> > is guaranteed not to leak. If you successfully enter the constructor,
> > shared_ptr takes responsibility for the pointer.
> >
> > The safe way to write the above is
> >
> > shared_ptr<string> p1(new string("text"));
> > shared_ptr<string> p2(new string("text2"));
> >
> > my_any_pair(p1, p2);
> >
> > or alternatively you need shared_ptr_new:
> >
> > my_any_pair(shared_ptr_new<string>("text"),
> > shared_ptr_new<string>("text2"));
>
> I'm sure you know this, but maybe Gary doesn't:
>
> boost::shared_ptr<string>(new string("text"))
>
> isn't any safer than
>
> std::auto_ptr<string>(new string("text"))
>
> in the sense that any expression (e.g. function invocation) with two such
> sub-expressions (e.g. parameters) can leak.

I'm sure we both understand each other but this is probably a bit confusing
to others. :-)

Let me clarify:

boost::shared_ptr<string>(std::auto_ptr<string>(new string("text")))

is no safer than

boost::shared_ptr<string>(new string("text"))

There's really no need for the intermediate auto_ptr here.

The caveat about temporary smart pointer objects still applies. My rule is
"never create an unnamed temporary smart pointer." The non-const reference
idiom tries to enforce this rule... although I have another reason for
preferring pass by non-const reference:

void f(T arg);

T t;

f(t);

// now t is unchanged, right?

--
Peter Dimov
Multi Media Ltd.

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