mercredi 29 août 2018

C++11 Range-based for loop for std::list

If I understand the range-based for loop correctly, which expands

for ( range_declaration : range_expression ) loop_statement

into

{
    auto && __range = range_expression ;
    for (auto __begin = begin_expr, __end = end_expr;
            __begin != __end; ++__begin) {
        range_declaration = *__begin;
        loop_statement
    }
}

thus incrementing the pointer, and if I understand that std::lists are internally implemented as doubly linked lists, isn't it correct to assume that something like this would not print 0 1 2 3, since the memory addresses are not sequential (implied by the ++__begin)?

std::list<int> myList = {0, 1};
std::list<int> otherList = {10, 11};
myList.push_back(2);
myList.push_back(3);

for(auto& i: myList)
    std::cout << i << " ";

And yet it does print correctly. So then, is std::list::iterator overriding the behavior of the operators used in the range-for-loop expansion?

This is of particular importance to me if I choose to implement my own range-for iterable data structures.

Aucun commentaire:

Enregistrer un commentaire