starriet 차주녕
starriet 차주녕

Reputation: 3968

Difference between auto& and auto&& in structured binding used in range-based for loop

(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

Upvotes: 0

Views: 43

Answers (0)

Related Questions