Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

May a random access iterator to end be incremented by zero?

The title says it all really. Given an iterator to end, may it be incremented by zero without invoking undefined behavior?

Case in point - does the following code work to return an iterator to the specified index - or to end if the index is out of range?

std::vector<Type>::iterator Class::fromIndex(size_t index) {
    return member_vector.begin() + std::min(index, member_vector.size());
}

If the behavior for std::advance or std::next are different that would be interesting to know as well, but here I am interested specifically in operator+.

like image 544
zennehoy Avatar asked May 03 '16 16:05

zennehoy


Video Answer


1 Answers

It's a well-defined no-op, say I.

Given an iterator to end, may it be incremented by zero without invoking undefined behavior? [..] I am interested specifically in operator+.

For random access iterators, table 115 under [random.access.iterators] tells us (under "Operational Semantics", and after "expanding" the meaning of the while loop there given) that (r += 0) ≡ r, so (.end() += 0) ≡ .end().

The definition for r + 0 is given in terms of that.

If the behavior for std::advance or std::next are different that would be interesting to know as well.

For everything else, std::next is defined in terms of std::advance, which in [iterator.operations] doesn't explicitly say that this is well-defined but it seems pretty obvious from the wording, which defers to the English-language definition for "increment"/"decrement": "Increments (or decrements for negative n) iterator reference i by n".

We know that the English-language "increment"/"decrement" by zero is a no-op in all practical terms.

like image 174
Lightness Races in Orbit Avatar answered Oct 19 '22 02:10

Lightness Races in Orbit