BlamKiwi
BlamKiwi

Reputation: 2193

Is erasing element after before_begin() defined in an empty std::forward_list?

Does this code have defined behaviour in the C++ standard library?

std::forward_list<T> list;
list.erase_after(list.before_begin());

Intuition would say no, but I haven't been able to locate the exact standards wording for this particular case.

Upvotes: 2

Views: 182

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171263

The precondition on erase_after is:

iterator erase_after(const_iterator position);

Requires: The iterator following position is dereferenceable.

So your example has undefined behaviour, because list is empty, so list.before_begin() is not incrementable, so there is no iterator following it.

If the list has at least one element then list.erase_after(list.before_begin()) is valid.

Upvotes: 6

Related Questions