views:

3349

answers:

5

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

+24  A: 

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.

Frank Krueger
+5  A: 

The STL containers need to be able to copy the items you store in them, and are designed to expect the original and the copy to be equivalent. auto pointer objects have a completely different contract, whereby copying creates a transfer of ownership. This means that containers of auto_ptr will exhibit strange behaviour, depending on usage.

There is a detailed description of what can go wrong in Effective STL (Scott Meyers) item 8 and also a not-so-detailed description in Effective C++ (Scott Meyers) item 13.

Garth Gilmour
+1 for the Effective STL reference.
DevSolar
+5  A: 

STL containers store copies of contained items. When an auto_ptr is copied, it sets the old ptr to null. Many container methods are broken by this behavior.

Dustin Getz
+37  A: 

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_pr 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 shared_ptr or weak_ptr smart pointers defined by TR1 or the boost libraries. Here is the boost library documentation for these smart pointers. Another alternative to consider in C++0x is unique_ptr.

Kevin
You should also consider the boost pointer containers, if you don't need shared ownership.
me22
+2  A: 

Two super excellent articles on the subject:

Lazer
@Lazer: Unnecessary necro, buddy.
DeadMG
@DeadMG: Why unnecessary?
Lazer
@Lazer: Because I think that in the intervening nearly two years, he probably dealt with the problem at hand.
DeadMG
@DeadMG: yes, you are correct. But that was not my purpose. If someone comes to this thread sometime and wants to learn about `auto_ptr` and stuff, these links will be helpful, I am sure.
Lazer
@Lazer: There's plenty of duplicates that are more recent.
DeadMG