Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transferring ownership to function with std::unique_ptr

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_ptrs. 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_ptrs? 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.

like image 374
newprogrammer Avatar asked Jul 16 '12 00:07

newprogrammer


People also ask

Can you pass unique_ptr to a function?

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.

Should I use unique_ptr or shared_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.

What is the use of std :: unique_ptr?

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.

How is unique_ptr implemented in C++?

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.


1 Answers

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.

like image 189
Puppy Avatar answered Sep 28 '22 08:09

Puppy