I heard auto_ptr
is being deprecated in C++11. What is the reason for this?
Also I would like to know the difference between auto_ptr
and shared_ptr
.
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++11 standard made auto_ptr deprecated, replacing it with the unique_ptr class template. auto_ptr was fully removed in C++17.
Since objects within an STL container must be copy-constructible and assignable, a compile time error is provided if an auto_ptr is used within a container. Algorithms, such as those involved in sorting STL containers, often copy objects while carrying out their tasks.
As for other differences, unique_ptr can handle arrays correctly (it will call delete[] , while auto_ptr will attempt to call delete .
The direct replacement for auto_ptr
(or the closest thing to one anyway) is unique_ptr
. As far as the "problem" goes, it's pretty simple: auto_ptr
transfers ownership when it's assigned. unique_ptr
also transfers ownership, but thanks to codification of move semantics and the magic of rvalue references, it can do so considerably more naturally. It also "fits" with the rest of the standard library considerably better (though, in fairness, some of that is thanks to the rest of the library changing to accommodate move semantics instead of always requiring copying).
The change in name is also (IMO) a welcome one -- auto_ptr
doesn't really tell you much about what it attempts to automate, whereas unique_ptr
is a fairly reasonable (if terse) description of what's provided.
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