I do not fully understand the benefits of unique_ptr
over auto_ptr
, or I am not yet fully convinced why we need to use unique_ptr
.
I see the following differences.
1) unique_ptr
supports arrays and thus the unique_ptr
destructor calls delete []
for arrays whereas the auto_ptr
destructor calls only delete
.
2) std::move()
has to be used instead of directly copying in case of unique_ptr
. But what advantage do we get with std::move()
? I will try to explain as below.
auto_ptr <int> p1 (new int);
auto_ptr <int> p2 = p1; // Now p1 is NULL and p2 exists with value of p1
unique_ptr <int> p1 (new int);
unique_ptr <int> p2 = std::move(p1); // Now p1 is NULL and p2 exists with value of p1
so what is the advantage we are going to get with this?
3) I read on the Internet that unique_ptr
can be used in containers. But if I understood correctly, this is not the great thing of unique_ptr
. Container function semantics are changed so now a days, copying is not getting done inside of the container functions. But how is this the great thing of unique_ptr
? Now that container functions are changed, why we cannot use auto_ptr
in containers?
unique_ptr
make it safe to use in STL containers.auto_ptr
is not container-safe. – Bladerauto_ptr
is still not container safe in C++11.unique_ptr
was created to address all of the shortcomings ofauto_ptr
, andauto_ptr
itself has not been changed. – Bladerauto_ptr
in containers, it's still not safe. – Chalcidiceauto_ptr
its still not possible. – Karolinekarolyauto_ptr
is not container safe because it does not support proper copy/move sematics that containers expect. It can steal ownership at times when stealing is not desired, thus objects might get freed prematurely.unique_ptr
does not suffer from that problem. Another advantage ofunique_ptr
is that it supports a customdeleter
, which makes it possible to have it manage resources that are not allocated withnew
ornew[]
.auto_ptr
does not support that. – Blader