Is it okay to do the following? The following code is using the vector v again in the loop (next iteration) after moving it.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void test(vector<int>&& v) {
cout << v.size() << endl;
v.push_back(5);
}
void test2(vector<int>& v) {
for (int i = 0; i < 4; i++) {
test(move(v));
}
}
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
test2(v);
}
Your code is correct, but the intention that you are communicating is wrong.
If someone sees the declaration of function test
he will think that when calling the function he is giving away the ownership of the variable that he is passing, because the variable will be moved.
In general, after a call to std::move(v)
you should not reuse v
.
What you should do in this case is declare test
as void test(std::vector<int>& v)
and you should call it just with test(v)
.
In this way it is clear that test
will modify v
, but you will be able to use it later.