Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does assigning make_unique require std::move() to an empty unique_ptr?

Tags:

c++

#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.

like image 437
AhSeng Fan Avatar asked Jan 18 '18 13:01

AhSeng Fan


2 Answers

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.

like image 86
StoryTeller - Unslander Monica Avatar answered Oct 20 '22 00:10

StoryTeller - Unslander Monica


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)...));
like image 36
Ron Avatar answered Oct 19 '22 23:10

Ron