[LC++]STL and auto_ptr woes

Jack Lloyd lloyd at acm.jhu.edu
Wed Mar 13 06:54:12 UTC 2002


> 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.

I didn't say delete it, I said remove it. Unless I am vastly confused about
how map works (and I'm quite certain I'm not), a map<T*> will not delete
it's T*s when it's destructor is called, nor when objects are taken out of
it with erase, or whatever that function is (I think it's erase).

> 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<>.

But his map contains a bunch of pointers. Those pointers should not change
value on their own, the map should never touch them. Perhaps the place in
memory where the pointers themselves are stored will change when the map
moves things around, but the map under discussion was holding pointers as
data items.

Definitely, taking the address of something stored in a container and using
it on a long term basis is a very bad idea. But that is not the case here.
Even if you left the pointer in the container, it would not affect the
container itself, it would just mean you would have to remember not to
deallocate that object again.

-Jack





More information about the tuxCPProgramming mailing list