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 swap
member function of std::unique_ptr
takes a non-const lvalue reference and the expression foo()
is an rvalue as foo
is 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:
foo().swap(myVar);
The simpler thing to do is a straight initialize:
std::unique_ptr<T> myVar(foo());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With