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+
.
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
orstd::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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With