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?
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.
As fas is i know, auto_ptrs have problems when copied, therefore should not be used in STL containers. shared_ptrs are your choice.
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).