1
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.

andyb
  • 95
  • 7

1 Answers1

2

From cppreference.com

Adding, removing and moving the elements within the list, or across several lists, does not invalidate the iterators currently referring to other elements in the list. However, an iterator or reference referring to an element is invalidated when the corresponding element is removed (via erase_after) from the list.

Adam
  • 16,808
  • 7
  • 52
  • 98