I saw the code below here. The description says:
We can also capture as a forwarding reference using auto&&. That is, auto&& will resolve to auto& for lvalue references, and auto&& for rvalud references. Here is an example of capturing the output from a range-based for loop over a temporary map.
I do understand the decaying of auto&&
to auto&
if the value referred to is an lvalue (so in this case there is no decay). What I struggling with, is to understand how the temporary map, the range based for loop and the moved values work together. Would you care to explain how these things work with each other and why it's ok to move from a temporary that is being iterated.
#include <iostream>
#include <map>
std::map<std::string, int> get_map()
{
return {
{ "hello", 1 },
{ "world", 2 },
{ "it's", 3 },
{ "me", 4 },
};
}
int main() {
for (auto&& [ k, v ] : get_map())
std::cout << "k=" << k << " v=" << v << '\n';
}