Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the behavior of erasing the `end()` of a `std::list`?

Tags:

c++

iterator

stl

I need to remove an element from a std::list after finding it with std::find. What is the behavior of calling std::list::erase with the end() of the list? My case is something like this:

std::list<T> mylist;
T value;
std::list::iterator it = std::find(mylist.begin(), mylist.end(), value);
std::list::iterator next = mylist.erase(it);

cplusplus.com says:

If position (or the range) is valid, the function never throws exceptions (no-throw guarantee). Otherwise, it causes undefined behavior.

but what I don't know is whether end() is considered valid there.

like image 966
Janoma Avatar asked Feb 27 '13 16:02

Janoma


1 Answers

That site uses the vague (and arguably incorrect) term "valid", but the library specification (C++11 23.2.3) uses the more specific term "dereferenceable" - meaning that the iterator must refer to an object. The past-the-end iterator is not dereferenceable, so erasing it gives undefined behaviour.

like image 76
Mike Seymour Avatar answered Nov 06 '22 06:11

Mike Seymour