void foo(std::vector<int> v)
Means that the function takes a std::vector<int>
object as a parameter. It's up to the caller to construct this parameter object however it wants, but then it's owned and used by foo
.
In the caller, you have:
foo(/**compiler constructs the v parameter from whatever is here**/);
Therefore:
vector<int> v1 = {1,2,3};
foo(v1); // This constructs the parameter `v` as a copy of `v1`.
Compared to
vector<int> v1 = {1,2,3};
foo(std::move(v1)); // This constructs the parameter `v` by moving from the value of `v1`.
Either is valid, but they do subtly different things.
void foo(std::vector<int>&& v)
Means that the function takes a reference as a parameter, that refers to a std::vector<int>
that is elsewhere, and also means that the caller should not use the parameter after this function is done with it, as the caller intends to invalidate it in some way.
The language helps prevent mistakes here by either
- forcing you to either pass a temporary (so the caller can't accidentally try to use the value of the referenced
vector
after foo
is complete),
- or forcing you to call
std::move
, to promise the compiler that you won't try to use the value of the referenced vector
after foo
is complete)