I'm reading some notes about shared pointers. They say the first attempt by STL with the auto_ptr had the following major drawbacks:
I understand the first two, but am unsure what the last one means.
Could someone please explain this.
Thanks.
Since the assignment-semantics was most-disliked feature, they wanted that feature to go away, but since there is code written that uses that semantics, (which standards-committee can not change), they had to let go of auto_ptr, instead of modifying it.
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 C++11 standard made auto_ptr deprecated, replacing it with the unique_ptr class template. auto_ptr was fully removed in C++17. For shared ownership, the shared_ptr template class can be used. shared_ptr was defined in C++11 and is also available in the Boost library for use with previous C++ versions.
This is because once you copy the auto_ptr
into a variable, you forfeit the ownership of the pointer to the new variable.
When you have:
void foo(std::auto_ptr<bar> x);
and you call foo
with an auto_ptr
, you make a copy of the auto_ptr
for foo
's use. This effectively transfers ownership to foo
and thus the pointer gets deleted after foo
is finished.
This is a really surprising behavior that made me definitively stop using auto_ptr
. For simple RAII inside a try
block (the primary use case of auto_ptr
, as described in books), use boost::scoped_ptr
.
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