c++iteratorlanguage-lawyer

C++ iterator dereference equality preservation


Is there any formal statement in C++ standard (or other trustworthy source) which requires the iterator to return the same value when dereferenced twice?

I see that equality_preservation doesn't explicitly require it (or I miss the point?).

So, what statement in standard exactly implies this expectation:

auto it = /* some iterator */;
auto v1 = *it;
auto v2 = *it;
assert(v1 == v2);

Solution

  • Both C++17/C++20 input iterators require the expression *it to be equality-preserving.

    [iterator.cpp17] describes the requirements for Cpp17InputIterator:

    Expression Return type Assertion/note
    *a reference, convertible to T Preconditions: a is dereferenceable. The expression (void)*a, *a is equivalent to *a. If a == b and (a, b) is in the domain of == then *a is equivalent to *b.

    And C++20 std::input_iterator needs to satisfy indirectly_readable, which explicitly requires the semantics in [iterator.concept.readable]:

    Given a value i of type I, I models indirectly_readable only if the expression *i is equality-preserving.