Consider the following function:
std::vector<int> pushIt(std::vector<int> v){
v.push_back(10);
return v;
}
int main(){
std::vector<int> vec;
vec = pushIt(std::move(vec));
}
my assumption is that the vector is moved into the function, modified and moved back to its original spot. This should result in simmilar behavior as passing it in as a non const reference. This seems to be quite valid behavior but a colleague fears undefined behavior. Is there anything I am missing here?
I would like to do this because the current function
void currentPushIt(std::vector<int>& v){
v.push_back(10);
}
has led to a lot of problems in code review because people overlook the fact that an innocent call to currentPushIt(v)
can invalidate iterators. Making them write v=pushIt(std::move(v))
should wake them up enough that they don't make the same mistakes.