How &&, range-based cycle and temporary work together?

I saw the code below here . The description says:

We can also record forwarding links using auto & &. That is, Auto && will solve auto for both lvalue links and auto && for rvalud links. The following is an example of capturing loop-based output from a time reference.

I understand decomposition auto&&into auto&if the value mentioned is an lvalue (so there is no decay in this case). What I'm struggling with is to understand how a time map, a range based on a loop and moved values, work together. Could you explain how these things work with each other and why it is normal to go from temporary to repeated.

#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';
}
+4
source share
1 answer

There are two different uses in this example auto&&, one visible, one hidden. To be as detailed as possible, the loop you have is expanding to:

{
    auto&& __range = get_map(); // the temporary get_map() is bound to a reference, which 
                                // extends its lifetime to the lifetime of the reference
                                // decltype(__range) is std::map<std::string, int>&&

    auto __begin = __range.begin();
    auto __end = __range.end();     // potential different type from __begin since C++17
    for (; __begin != __end; ++__begin) {
        auto&& __elem = *__begin;  // this is your structured binding declaration
                                   // *__begin is an lvalue, so decltype(__elem) is
                                   // std::pair<std::string const, int> const&


        // the actual destructuring here
        std::string const& k = std::get<0>(__elem);    
        int const& v         = std::get<1>(__elem);

        // now your body
        std::cout << "k=" << k << " v=" << v << '\n';
    }
}

Hence:

why is it normal to switch from temporary to repeated.

. map __range, , . .


, :

auto&& auto&, lvalue

. -, "" - - , , , , - . , auto&& auto&. , lvalue, auto&& auto& . rvalue, auto&& ( rvalue), auto& .

+1

Source: https://habr.com/ru/post/1683282/


All Articles