Search code examples
c++algorithmlistcontainersstdlist

std::list is a cyclic list!! wait, what?


I was writing a test program and found a very interesting case of std::list's behavior.

#include <list>
#include <algorithm>
#include <iostream>

int main()
{
    std::list<int> mylist;
    std::list<int>::iterator iter;
    for(int i=3; i<10; ++i){
        mylist.push_back(i);
    }
    iter = mylist.begin();
    iter--;
    iter--;
    std::cout<<*iter<< std::endl;
    std::cout<<std::distance(mylist.end(), mylist.begin())<<std::endl;
}

The output is:

9  
1  

If I am not mistaken, this behavior is related to cyclic lists. I have never met a forum, book or discussion, in which is mentioned that standard list is a cyclic list. My GCC version is 4.1.2. So am I correct? Is standard std::list a cyclic list?


Solution

  • No, std::list is not cyclic. Your code has undefined behavior when you decrement that iterator. It also has undefined behavior when you call std::distance(mylist.end(), mylist.begin()), because mylist.begin() is not reachable by incrementing mylist.end().

    Note that when you invoke undefined behavior, std::list may very well appear to be cyclic, since "std::list appearing to be cyclic" fits in the range of allowable behaviors when the behavior is undefined. That range being, any behavior whatsoever.