Search code examples
c++c++11move

Move unique_ptr ownership from one class to another


I want to create a unique pointer in one class, class A, then pass on the ownership to another class, class B. Am I ok doing such a thing?

The code below gives me error in getC: error: call to deleted constructor of 'std::unique_ptr<C>

What am I doing wrong?

class A {
...
  void func(shared_ptr<B> Bptr) {
   A_pass = make_unique<C>();
   Bptr->setPass(move(A_pass));
  }
  unique_ptr<C> getC()
  {
    return A_pass;
  }
 unique_ptr<C> A_pass;
};

class B {
...
 void setPass(unique_ptr<C> pass_ptr){
  B_pass = move(pass_ptr);
 }
 unique_ptr<C> B_pass;
}

edit: update the question


Solution

  • Your question does not state where the compiler error occurs, but I would guess it’s the getC() member function:

    class A {
    ...
     
      unique_ptr<C> getC()
      {
        return A_pass;
      }
     unique_ptr<C> A_pass;
    };
    

    The function as written is attempting to copy A_pass, which of course is not possible for the std::unique_ptr<T> type.

    You can rewrite it to explicitly move from the source (I’m not able to test this):

    unique_ptr<C> A::getC() {
        return A_pass.release();
        // alternative: return unique_ptr<C>(std::move(A_pass));
    }