A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.
An unique_ptr has exclusive ownership of the object it points to and will destroy the object when the pointer goes out of scope. A unique_ptr explicitly prevents copying of its contained pointer. Instead, the std::move function has to be used to transfer ownership of the contained pointer to another unique_ptr .
Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.
An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.
What is generally the proper way to forward an std::unique_ptr?
The following code uses std::move
, which I thought was the considered practice, but it crashes with clang.
class C {
int x;
}
unique_ptr<C> transform1(unique_ptr<C> p) {
return transform2(move(p), p->x); // <--- Oops! could access p after move construction takes place, compiler-dependant
}
unique_ptr<C> transform2(unique_ptr<C> p, int val) {
p->x *= val;
return p;
}
Is there a more robust convention than simply making sure you get everything you need from p
before transferring ownership to the next function via std::move
? It seems to me using move
on an object and accessing it to provide a parameter to the same function call could be a common mistake to make.
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