Why is auto_ptr deprecated? It takes ownership of the pointer in a way that no two pointers should contain the same object. Assignment transfers ownership and resets the rvalue auto pointer to a null pointer. Thus, they can't be used within STL containers due to the aforementioned inability to be copied.
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.
The standard committee decided that pointers will be deprecated in C++20 and will with very high probability be removed in C++23. To be honest, what seems like a revolution is only the last step in a long evolution.
In short: Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.
UPDATE: This answer was written in 2010 and as anticipated std::auto_ptr
has been deprecated. The advice is entirely valid.
In C++0x std::auto_ptr
will be deprecated in favor of std::unique_ptr
. The choice of smart pointer will depend on your use case and your requirements, with std::unique_ptr
with move semantics for single ownership that can be used inside containers (using move semantics) and std::shared_ptr
when ownership is shared.
You should try to use the smart pointer that best fits the situation, choosing the correct pointer type provides other programmers with insight into your design.
Yes, as of today auto_ptr
will be deprecated in C++0x and you should use unique_ptr
instead. From the latest draft standard (n3035), section D.9
The class template
auto_ptr
is deprecated. [ Note: The class templateunique_ptr
(20.9.10) provides a better solution. —end note ]
Until the standard is ratified, it's always possible that the committee will revise this decision although I feel that is unlikely for this decision.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With