The following code will throw a warning:
warning C4239: nonstandard extension used : ‘argument’ : conversion from ‘std::unique_ptr<_Ty>’ to ‘std::unique_ptr<_Ty> &’
std::unique_ptr<T> foo() { return std::unique_ptr<T>( new T ); }
std::unique_ptr<T> myVar;
myVar.swap(foo());
I would like to know what is the proper way to handle this situation.
The
swapmember function ofstd::unique_ptrtakes a non-const lvalue reference and the expressionfoo()is an rvalue asfoois a function returning an object (as opposed to a reference). You cannot bind an rvalue to a non-const lvalue reference.Note that you can do the swap the other way around:
The simpler thing to do is a straight initialize: