Why is it wrong to use std::auto_ptr<>
with standard containers?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
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 storeauto_ptrs
in the containers.Two super excellent articles on the subject:
C++03 Standard (ISO-IEC 14882-2003) says in clause 20.4.5 paragraph 3:
C++11 Standard (ISO-IEC 14882-2011) says in appendix D.10.1 paragraph 3:
C++14 Standard (ISO-IEC 14882-2014) says in appendix C.4.2 Annex D: compatibility features:
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:
To overcome this limitation, you should use the
std::unique_ptr
,std::shared_ptr
orstd::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.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.
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.