Passing vector of unique_ptr with move semantics in c++

694 Views Asked by At

I am learning CPP++14 move semantics.While writing a small code I observed some weird behavior. I am moving vector of unique ptr to a function using r-value refrence. on debuuging I found that the changes are being applied to the moved object also. Why am I observing this hcnage even the object is moved? Whats does the move do in following code?

void func(std::vector<std::unique_ptr<int>> && vect) {
    vect.emplace_back(std::move(std::make_unique<int>(3)));
    return ;
}

int  main() {
    std::vector<std::unique_ptr<int>> a;
    func(std::move(a));
    cout<<(*(a[0]))<<endl;
    return 0;
}
1

There are 1 best solutions below

9
On

Whats does the move do in following code?

Move operation is not performed in func(std::move(a)); in fact, std::move just performs conversion and produces an rvalue (xvalue) expression, which is just bound to the rvalue reference parameter vect of func. Then any modification on vect inside func has effect on the argument (i.e. a) too, they refer to the same object.

In particular, std::move produces an xvalue expression that identifies its argument t. It is exactly equivalent to a static_cast to an rvalue reference type.

If you change the parameter to pass-by-value, then you'll see move operation is performed. And given the usage you showed, just pass-by-lvalue-reference seems less confusing (and no need to use std::move on argument again).

BTW: In vect.emplace_back(std::move(std::make_unique<int>(3))); the usage of std::move is superfluous, std::make_unique<int>(3) been an rvalue expression.