0

I was reading about passing unique_ptr to a function here:

Can I pass a unique_ptr's reference to a function?

The winner answer tell that this function takes ownership:

void func1(unique_ptr<Clss>&& moved_obj) // this function takes ownership
{
    //do something with the moved_obj

    moved_obj.reset();
}

I did a small example to understand:

// The functions used for that
void pass_unique_by_copy(std::unique_ptr<int> T) { *T = 9; }
void pass_unique_by_ref(std::unique_ptr<int> &T) { *T = 9; }
void pass_unique_by_move(std::unique_ptr<int> &&T) { *T = 9; }

 
 // main code
 std::unique_ptr<int> g = std::make_unique<int>();
 pass_unique_by_copy(std::move(g));
 assert(g == nullptr);
 cout << "The ownership as given\n";
  
 // passed as reference is ok 
 g = std::make_unique<int>();
 pass_unique_by_ref(g);
 assert(g == nullptr);
 cout << "Still the owner\n";
  

 // moved ownership
 pass_unique_by_move(std::move(g));
 assert(g == nullptr);          // --> g is not nullptr , why ?
 cout << "content was moved lost ownership\n"; 

The output should be :

The ownership as given
Still the owner
content was moved lost ownership

But It's been held on the last assert

1- If I am moving the ownership to the function g should be nullptr after isn't ?

2 - why the guy put a reset inside the function ? I didn't get it could someone explain me ?

  • That answer is incorrect. A rvalue reference parameter does not mean the function takes ownership. Only if it actually moves the thing it is referring to will ownership actually be transferred. Otherwise you just have a reference to a `unique_ptr` like the second function, albeit one that lets you modify that `unique_ptr` object. I've left a comment on that answer, hopefully the OP will reply. – NathanOliver Sep 16 '22 at 12:27
  • Thanks for the answer, but if I understood clear this `pass_unique_by_move(std::move(g));` is equivalent to pass as a reference ? But I am moving something which accepts a rvalue. it makes me more confused. – Lord Feistel Sep 16 '22 at 12:50
  • `move` doesn't actually *move* anything. All it does is return a rvalue reference to the passed in object. To actually move something you need to give it to another object like `foo some_name = std::move(some_object);` Just doing `foo&& some_name = std::move(some_object);` just makes `some_name` a reference to `some_object`. – NathanOliver Sep 16 '22 at 12:54

0 Answers0