Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cant I swap a unique_ptr with a unique_ptr returned by a function?

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.

like image 825
aCuria Avatar asked Sep 14 '25 21:09

aCuria


1 Answers

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());
like image 87
CB Bailey Avatar answered Sep 17 '25 12:09

CB Bailey