#include <memory>
using namespace std;
int main()
{
unique_ptr<int> a;
// Do something....
// Case 1
a = make_unique<int>(5);
// Case 2
a = std::move(make_unique<int>(5));
return 0;
}
What I'm really asking is:
Is std::move required to assign a temporary unique_ptr to an empty unique_ptr? Both cases can be compiled successfully but I wonder if there is any difference between them.
It's not, because in both cases the expression may bind to an rvalue reference.
In the first, std::make_unique
already returns a pure rvalue.
In the second, std::move
does a cast to an rvalue reference, it's redundant.
It also doesn't matter if the destination object is empty or not. The mere act of invoking assignment doesn't depend on how the reference it received was bound. The result would be the same, the previous (possibly non-existent) resource in the target will be replaced by the one "stolen" from the source.
You don't need to use the std::move
when assigning a value to a std::unique_ptr
pointer via std::make_unique. This goes both for the initialization:
std::unique_ptr<int> a = std::make_unique<int>(5);
and the assignment:
std::unique_ptr<int> a;
a = std::make_unique<int>(5);
The implementation already does the forwarding for you:
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
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