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;
}
Move operation is not performed in
func(std::move(a));in fact,std::movejust performs conversion and produces an rvalue (xvalue) expression, which is just bound to the rvalue reference parametervectoffunc. Then any modification onvectinsidefunchas effect on the argument (i.e.a) too, they refer to the same object.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::moveon argument again).BTW: In
vect.emplace_back(std::move(std::make_unique<int>(3)));the usage ofstd::moveis superfluous,std::make_unique<int>(3)been an rvalue expression.