“Downcasting” unique_ptr to unique_ptr

I’d create a couple of function templates, static_unique_ptr_cast and dynamic_unique_ptr_cast. Use the former in cases where you’re absolutely certain the pointer is actually a Derived *, otherwise use the latter. template<typename Derived, typename Base, typename Del> std::unique_ptr<Derived, Del> static_unique_ptr_cast( std::unique_ptr<Base, Del>&& p ) { auto d = static_cast<Derived *>(p.release()); return std::unique_ptr<Derived, Del>(d, std::move(p.get_deleter())); } template<typename … Read more

Differences between std::make_unique and std::unique_ptr with new

The motivation behind make_unique is primarily two-fold: make_unique is safe for creating temporaries, whereas with explicit use of new you have to remember the rule about not using unnamed temporaries. foo(make_unique<T>(), make_unique<U>()); // exception safe foo(unique_ptr<T>(new T()), unique_ptr<U>(new U())); // unsafe* The addition of make_unique finally means we can tell people to ‘never’ use new … Read more

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

Here are the possible ways to take a unique pointer as an argument, as well as their associated meaning. (A) By Value Base(std::unique_ptr<Base> n) : next(std::move(n)) {} In order for the user to call this, they must do one of the following: Base newBase(std::move(nextBase)); Base fromTemp(std::unique_ptr<Base>(new Base(…)); To take a unique pointer by value means … Read more

Returning unique_ptr from functions

is there some other clause in the language specification that this exploits? Yes, see 12.8 §34 and §35: When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object […] This elision of copy/move operations, called copy elision, is permitted […] in a return statement in a function … Read more