tags:

views:

84

answers:

3

I know containers of auto pointers should not be used and can cause problems. What is the actual reason for that? Is there any other kind of "smart" pointer which is safe to use in a container?

+10  A: 

Container elements should be truly copyable; auto_ptr's are not. If you make a copy, the original is modified (it loses ownership). A boost::shared_ptr can be copied, as the two pointers will share ownership afterwards. Thus, it can be used in a STL container.

MSalters
+1 Note that `boost::shared_ptr<>` became `std::tr1::shared_ptr<>` (if your compiler/std lib supports TR1) and `std::shared_ptr<>` (if your compiler/std lib supports C++11).
sbi
Many thanks. For who is interested, meanwhile I've realized there a chapter (item 8) answering this very same question in the book Effective STL.
Gianluca
I agree on your auto_ptr comment, but I would not recommend shared_ptr for copying. As neither auto_ptr or shared_ptr does what is asked on copy. Shared ownership is not a copy. If you copy an object, do you expect alteration of the copy to affect the source? If you want an object to be copyable, and it contains a pointer. You should create your own copy constructor to make sure that the copy will have no hidden links to the source.
daramarak
@damarak: a copy of a _pointer_ is not a copy of an _object_. If I copy a pointer, I expect it to be identical to the original pointer. Therefore both point to the same object. Shared_ptr's copy constructor does precisely that.
MSalters
A: 

As fas is i know, auto_ptrs have problems when copied, therefore should not be used in STL containers. shared_ptrs are your choice.

Tapdingo
+3  A: 

The problem is with the copy semantics in auto_ptr. When you assign an two auto pointers, the RHS will yield ownership of the memory to the LHS. This implies that the assignment signature is: auto_ptr& operator=( auto_ptr& rhs ) (note that there is no const in the RHS), so in many cases it won't even compile.

There are other smart pointers that can be used with containers. In the TR1 there is a shared_ptr modeled after boost::shared_ptr (in some compilers it is exactly the code in boost just copied and with the namespaces changed). Boost also has boost::unique_ptr that will be the replacement for auto_ptr in the upcoming standard. It models single ownership with move semantics so that it can be used inside without the extra cost of using shared_ptr (not that in most cases the cost is noticeable).

David Rodríguez - dribeas