Car Signs Containers

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

+2


a source to share


3 answers


The container elements must be truly copyable; auto_ptr is not. If you make a copy, the original is changed (it loses ownership). Boost :: shared_ptr can be copied, since then the two pointers will jointly own the property. So it can be used in an STL container.



+11


a source


The problem lies in the semantics of copying in auto_ptr

. When you assign two automatic pointers, RHS will transfer ownership of the LHS. This means that the assignment signature is: auto_ptr& operator=( auto_ptr& rhs )

(note that there is not in RHS const

), so in many cases it won't even compile.



There are other smart pointers that can be used with containers. In TR1 there is shared_ptr

, modeled after boost::shared_ptr

(in some compilers, the code in boost is just copied and with changed namespaces). Boost also has boost::unique_ptr

one that will replace auto_ptr

in the upcoming standard. It models a single property with move semantics, so it can be used internally at no additional cost to use shared_ptr

(not so that the cost is noticeable in most cases).

+3


a source


As far as I know, auto_ptrs have copy problems and therefore should not be used in STL containers. shared_ptrs is your choice.

0


a source







All Articles