C++ Logo

std-discussion

Advanced search

erase and iterator invalidation

From: Yongwei Wu <wuyongwei_at_[hidden]>
Date: Tue, 12 Dec 2023 12:42:32 +0800
In the case of erase in the following form:

constexpr iterator erase(const_iterator);

basic_string does not say anything about iterator and reference
invalidation, while vector specifically says erase "invalidates
iterators and references at or after the point of the erase".

Tests with debugging libraries also show that `c.erase(it)` is OK in
the case of string, but causes runtime errors in the case of vector.
`it = c.erase(it)` can work around this issue. The Compiler Explorer
test for "bad" vector::erase is here:

https://godbolt.org/z/YEMxfaK1a

I have trouble imagining why `c.erase(it)` is wrong usage for vector
but OK for string. `it` naturally points to the next element, doesn't
it?

My question is:

1. Is the difference intentional?
2. Why is it specified that the iterator at the point of the
vector::erase is invalidated?

I think the answer is Yes for the first question. So my main question
is the second: Under which circumstance will it really cause troubles
in an implementation? After all, `c.erase(it)` does seem to work well
in a loop in non-debugging builds.

Thanks in advance for any replies.

-- 
Yongwei Wu
URL: http://wyw.dcweb.cn/

Received on 2023-12-12 04:42:46