Storing pointers in STL containers

Need to store objects in an STL container? Need polymorphic behaviour meaning you’ll need to store pointers to a base class? Want to use a smart pointer to avoid memory leaks? Planning on using auto_ptr because it’s available as part of C++? Before you go any further, try this little quiz.

Question: I should use auto_ptr if I want to store pointers to heap allocated objects in STL containers, right?

Answer: No… no no no!

Why?

The C++ standard explicitly states that an STL element must be “copy-constructible” and “assignable”. It also explicitly states that the behaviour of storing an auto_ptr in an STL container is undefined. Ok, fair enough… but why?

The auto_ptr has move semantics and not copy or reference semantics. This means, if you assign it to another auto_ptr the pointer the new auto_ptr takes ownership of the resource being managed and the old auto_ptr has its internal pointer set to NULL. Things in an STL container have a habit of getting copying about (either explicitly or implicitly) and so the auto_ptrs you store in there end up being arbitrarily set to NULL.

If you need a good reference covering smart pointers, take a look at the shared_ptr, which is part of Boost.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.