Advantages of unique_ptr over auto_ptr?
I don't fully understand the benefits unique_ptr
over auto_ptr
, or I'm not completely convinced yet why we need to use unique_ptr
.
I see the following differences.
1) unique_ptr
supports arrays and hence the destructor unique_ptr
calls delete []
for arrays whereas the destructor auto_ptr
only calls delete
.
2) std::move()
should be used instead of direct copy in case unique_ptr
. But what advantage do we get with help std::move()
? I will try to explain as shown 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 what unique_ptr
can be used in containers. But if I understood correctly, this is not very good for unique_ptr
. The semantics of the container function changes so that now days, copying is not done inside the container functions. But how is this great thing unique_ptr
? Now that the container functions have changed, why can't we use auto_ptr
in containers?
unique_ptr
forces you to be explicit about the transfer of ownership, which is why it is displayed and cleared in the code. It is auto_ptr
too easy to get a silent transfer of ownership with help , and when reading the code, it is not always clear if the ownership is being transferred, and if so, whether it was intended by the author of the code or is a mistake! When you see unique_ptr
used with std::move
, it is obvious that the purpose is to transfer ownership.
unique_ptr
correctly supports the semantics of movement, so it enables the transfer of ownership of the transmission time and of moving objects (i.e. rvalues ). Containers can detect that a type is "moving" and act accordingly. auto_ptr
is unaware of move semantics and transfers ownership of lvalues or rvalues, so containers treat it as a normal copyable object, but it does not behave like one as it changes its origin when copying.
auto_ptr
was helpful when used carefully, but it was too easy to misuse and write dangerous code. It's time to die. unique_ptr
supports everything it auto_ptr
can do, but is safe by default (you have to try and use it incorrectly) and also has additional features like custom deleters and support for arrays.