I am trying to learn how to use smart pointers and understand ownership. When I pass an auto_ptr
to a function by value, the function takes exclusive ownership of that pointer. So when the function finishes up, it deletes the pointer that I passed to it.
However, I get a compile error when I try doing this with a unique_ptr
, as if copy assignment is disabled for unique_ptr
s. Passing a unique_ptr
by reference does not seem to transfer ownership, it merely gives the function a reference to the unique_ptr
.
How do I get auto_ptr
's behavior with passing ownership to function to work with unique_ptr
s? I would appreciate a link to a detailed tutorial on unique_ptr
, as so far the ones I've read seem to only talk about auto_ptr
or talk about the smart pointers available with Boost and seem to ignore unique_ptr
because shared_ptr
covers it.
Why can I not pass a unique_ptr into a function? You cannot do that because unique_ptr has a move constructor but not a copy constructor. According to the standard, when a move constructor is defined but a copy constructor is not defined, the copy constructor is deleted.
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.
std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.
I have following C++ code snippet, which implements a unique pointer logic: template<typename T> class unique_ptr { private: T* _ptr; public: unique_ptr(T& t) { _ptr = &t; } unique_ptr(unique_ptr<T>&& uptr) { _ptr = std::move(uptr. _ptr); uptr.
However, I get a compile error when I try doing this with a unique_ptr, as if copy assignment is disabled for unique_ptrs.
It is. unique_ptr
has one, and only one, owner. It cannot be copied because that would result in two owners. In order to pass it by value into another function, the original owner must relinquish ownership, using std::move
.
In order to use unique_ptr
, you must understand move semantics.
auto_ptr
is simply a hacky approximation to true move semantics that doesn't actually work. It's best to simply forget this class ever existed.
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