Why is it wrong to use std::auto_ptr<> with standard containers?

The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. std::auto_ptr does not fulfill this requirement.

Take for example this code:

class X
{
};

std::vector<std::auto_ptr<X> > vecX;
vecX.push_back(new X);

std::auto_ptr<X> pX = vecX[0];  // vecX[0] is assigned NULL.

To overcome this limitation, you should use the std::unique_ptr, std::shared_ptr or std::weak_ptr smart pointers or the boost equivalents if you don't have C++11. Here is the boost library documentation for these smart pointers.


The copy semantics of auto_ptr are not compatible with the containers.

Specifically, copying one auto_ptr to another does not create two equal objects since one has lost its ownership of the pointer.

More specifically, copying an auto_ptr causes one of the copies to let go of the pointer. Which of these remains in the container is not defined. Therefore, you can randomly lose access to pointers if you store auto_ptrs in the containers.


Two super excellent articles on the subject:

  • Smart Pointers - What, Why, Which?
  • Guru of the Week #25