How do I pass a unique_ptr argument to a constructor or a function?

I’m new to move semantics in C++11 and I don’t know very well how to handle unique_ptr parameters in constructors or functions. Consider this class referencing itself:

#include <memory>

class Base
{
  public:

    typedef unique_ptr<Base> UPtr;

    Base(){}
    Base(Base::UPtr n):next(std::move(n)){}

    virtual ~Base(){}

    void setNext(Base::UPtr n)
    {
      next = std::move(n);
    }

  protected :

    Base::UPtr next;

};

Is this how I should write functions taking unique_ptr arguments?

And do I need to use std::move in the calling code?

Base::UPtr b1;
Base::UPtr b2(new Base());

b1->setNext(b2); //should I write b1->setNext(std::move(b2)); instead?

7 Answers
7

Leave a Comment