c++unique-ptrmove-semanticsstdmove

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


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


Solution

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