I recently wondered about the behavior of modifying sequence container operations (e.g. insert, erase) when called with iterators that refer to elements not controlled by the container whose member function is called.
int main() {
std::vector<int> a = {1,2,3}, b = {1,2,3};
a.erase(b.begin());
}
I know that this will lead to undefined behavior, but where exactly is this forbidden by the standard?
(The “controlled by” terminology is what is used in the Dinkumware documentation and is also used in the standard for some valarray operations although I could not find it with general sequence containers.)
It is not directly forbidden, it just hasn’t any defined behaviour – thus UB.
In the C++11 standard this sequence container operation is defined in table 100, where the preconditions for
a.erase(q)areAnd if it’s not, the operation isn’t valid.