9

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.

newprogrammer
  • 2,514
  • 2
  • 28
  • 46

1 Answers1

14

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.

Community
  • 1
  • 1
Puppy
  • 144,682
  • 38
  • 256
  • 465
  • @DeadMG That is a fantastic linked answer. I'm still wondering about one thing though: What happens when the `unique_ptr` that was passed goes out of scope? Is it like deleting NULL? – newprogrammer Jul 16 '12 at 01:06
  • 1
    @newprogrammer: Nothing. It owns no resource, so nothing happens. – Puppy Jul 16 '12 at 01:13