0

(Please let me know if this is a duplicate. I tried to search previous questions but couldn't find the same one.)

When structured binding is used in a range-based for loop like this:
for (auto & [k, v] : myMap) {...} or
for (auto && [k, v] : myMap) {...}

What is the exact difference between using auto& and auto&&? It seems they works the same way, at least the results are the same.

Which should I use, what is the idiomatic way?

(The below example compiles with no problem)

std::map<std::string, int> get_map() {
    return {
        { "abc", 3 },
        { "great", 5 },
    };
}

int main() {
    for (auto& [ k, v ] : get_map()) { 
        std::cout << k << " " << ++v << '\n'; 
    }
    std::cout << "----------------" << '\n'; 
    for (auto&& [ k, v ] : get_map()) { 
        std::cout << k << " " << ++v << '\n'; 
    }
}

// output:
// abc 4
// great 6
// ----------------
// abc 4
// great 6
starriet
  • 2,565
  • 22
  • 23
  • Related/dupe: [What's the difference between & and && in a range-based for loop?](https://stackoverflow.com/questions/29320575/whats-the-difference-between-and-in-a-range-based-for-loop) and [What does auto&& tell us?](https://stackoverflow.com/questions/13230480/what-does-auto-tell-us/13242177#13242177) – Jason Sep 29 '22 at 07:39
  • @JasonLiam Thanks. A few questions: 1) The answer of your first link says both `auto&` and `auto&&` are equivalent to `T&`, for standard containers. Then, why are there so many codes using `auto&&` for typical standard containers? 2) I've read your second link before I post this, but couldn't get this part: *"auto& => will only bind to modifiable lvalues"*. In the code example in the question, `auto&` binds to a modifiable rvalue, doesn't it? – starriet Sep 29 '22 at 07:56
  • 1
    To answer your first question in the previous comment, it is just preference to use `auto&` or `auto&&` in range based for loop. Note i am talking only about the use of `auto&&` and `auto&` in a range based for loop and not in a statement like `auto& r = get_map();` which won't compile as expected. I've removed the second link from dupe list. It is not much related as that second link talks about use of `auto&` and `auto&&` in a declaration statement and not in a range based for loop. – Jason Sep 29 '22 at 08:26
  • For future reference: See [§8.6.4 The range-based for statement] of C++20 standard document, to understand why `for (auto& [ k, v ] : get_map()) {...}` works (even if it's `auto&`, not `auto&&`). Actually, it's irrelevant because get_map() is bound with `auto&&` anyways(just see §8.6.4 as mentioned). – starriet Sep 30 '22 at 09:17

0 Answers0