samedi 18 avril 2015

std::forward_list::push_front while iterating


std::forward_list<int> foo {1,2,3,4,5};

for(int i:foo)
{
if(i==1) foo.push_front(0);

std::cout << i << std::endl;
}


I've tested it on Visual Studio and coliru, and from my understanding of how a single linked list is designed there shouldn't be a problem. However, I have little understanding of the internals of forward_list, or stl containers and iterators in general, so I wanted to ask to make sure:


Is above code safe? Or am I invoking UB and it just happens to not start the apocalypse in my small test.


Aucun commentaire:

Enregistrer un commentaire