C++ Logo

std-discussion

Advanced search

Re: erase and iterator invalidation

From: Yongwei Wu <wuyongwei_at_[hidden]>
Date: Tue, 12 Dec 2023 17:37:28 +0800
On Tue, 12 Dec 2023 at 14:14, Daniel Krügler <daniel.kruegler_at_[hidden]> wrote:
>
> Am Di., 12. Dez. 2023 um 05:42 Uhr schrieb Yongwei Wu via
> Std-Discussion <std-discussion_at_[hidden]>:
> >
> > 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".
>
> That's not quite right. We have [string.require] p4, which says:
>
> 4 References, pointers, and iterators referring to the elements of a
> basic_string sequence may be invalidated
> by the following uses of that basic_string object:
> (4.1) — Passing as an argument to any standard library function taking
> a reference to non-const basic_string
> as an argument.
> (4.2) — Calling non-const member functions, except operator[], at,
> data, front, back, begin, rbegin, end,
> and rend.
>
> So, bullet (4.2) applies for erase, which is a non-const member
> function that is not excluded by the listed functions.

After reading the sections about insert, I guess you are probably
right. The standard specifies string and vector in different ways. In
vector, details about iterator invalidation are discussed; but no such
discussion happens about basic_string::insert. But we all know
iterators may be invalidated after an insert.

So it seems the standard simply provides very weak guarantees about
the erase behaviour, and there are really no intended differences
between basic_string::erase and vector::erase regarding iterator
validation. Am I right?

So, going further, it also means it is not due to practical
considerations that would make the `position` iterator be invalidated.
It is just specified so, maybe out of consistency considerations?

Received on 2023-12-12 09:37:40