Possible Duplicate:
What is the advantage of using universal references in range-based for loops?
To iterate over the elements of a vector<int>
to read them, I think the following usage of C++11 range-based for with auto
is correct:
std::vector<int> v;
....
for (auto n : v)
{
// Do something on n ...
....
}
If the elements stored in the container are not simple integers, but something "heavier", like say std::string
s, my understanding is that to iterate over them in a vector<string>
the correct usage of range-based for + auto
is:
std::vector<std::string> v;
....
for (const auto& s : v)
{
// Do something on s ...
....
}
The use of const &
avoids useless deep-copies, and should be OK since the loop code is just observing the content of the vector.
Is my understanding correct so far?
Now, I saw code that uses another form of auto
in range-based for loops: auto&&
, e.g.:
for (auto&& elem : container)
....
What is this usage good for? What is the advantage of using r-value references (&&
) with range-based for loops? In what cases should we use this style?