C++

Asked • 07/07/19

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

<!-- language-all: lang-cpp --> 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?

1 Expert Answer

By:

Cody H. answered • 05/30/21

Tutor
4.7 (10)

C++ / python Software Engineer for Autonomous Vehicle Companies

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.