Here is simplified code snippet:
void printArray(vector<int> arr)
{
vector<int> temp_a = arr; //<<------- move here?
for(int i = 0; i < temp_a.size(); ++i)
cout << temp_a[i] << endl;
}
Will there be a move there?
No, the move constructor of std::vector
won't be used in that instance; the copy constructor will be used instead.
In general, moves don't happen implicitly, because every expression made of an identifier (unqualified-id) is an lvalue (e.g. arr
is an lvalue). The move constructor accepts a std::vector&&
rvalue reference, and that cannot bind to lvalues. As a result, the copy constructor is called.
The only exception to this rule is in a return statement:
// if arr is a local variable, it will be moved implicitly here
return arr;
To move the vector in your case, you must use std::move
:
vector<int> temp_a = move(arr);
However, the whole function could also be simplified to:
void printArray(const vector<int>& arr)
{
for(int x : arr)
cout << x << '\n';
}