Ownership not delegated to a function using unique_ptr < T > && and std::move ( )

79 views Asked by At

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 ?

0

There are 0 answers