[LC++]STL and auto_ptr woes

George T. Talbot george at phat.com
Wed Mar 13 04:08:04 UTC 2002


----- Original Message -----
From: "Jack Lloyd" <lloyd at acm.jhu.edu>
To: <tuxcpprogramming at lists.linux.org.au>
Sent: Tuesday, March 12, 2002 11:45 AM
Subject: Re: [LC++]STL and auto_ptr woes


> On Mon, 4 Mar 2002, Charles Randle wrote:
>
> > However when I assign the pointers to an auto_ptr object as in:
> >
> > ::std::auto_ptr<someobject1> vb = BigMap2["located"].second.first;
> >
> > the compiler gives the following error:
> >
> > simple.cpp:52:conversion from 'someobject1*' to non-scalar type
> > 'std::auto_ptr<someobject1>' requested
>
> I don't see why you would want to do that, *unless* you want the objects
> deleted when you exit the function you are creating the auto_ptr in. If
> that is the case, you should remember to remove said objects from the map,
> otherwise, when you delete the remaining objects in the map, you'll delete
> that object twice, once when the auto_ptr goes out of scope and once when
> the map is cleaned out.
> -Jack

Yeah, but it's not going to work.  When you delete it from the map, it'll
delete the object, then when vb goes out of scope, it'll get deleted again.
I don't think it's going to work at all.

Moreover, the container is free to change the address of elements in the
container when insertions/deletions happen as long as any ordering
guarantees with iterators are preserved.  This probably also means calling
constructors and destructors internal to the container, and will probably
give unpredictable results with auto_ptr<>.

The honest answer:  Don't use auto_ptr<> in Standard C++ Library containers.
It's a bad idea.  auto_ptr<> should only be on the stack.

--George






More information about the tuxCPProgramming mailing list