2

For input iterators, what are the requirements for comparing equality if one of the iterators has been invalidated?

input_iter x = foo();
input_iter y = x;
++x;
return x == y;  // What must this return?

In the above example, dereferencing y would obviously be undefined, but is the result of an equality comparison like this defined? Reading cppreference.com, it's definitely the case that two input iterators must compare true if they actually are the same, since input iterators must satisfy EqualityComparable, but I don't actually see anything that says what the result must be if the are not the same. Am I allowed to always return true from operator== (except when comparing against the end iterator)?

IanPudney
  • 5,941
  • 1
  • 24
  • 39
  • It seems implied that you should return `false` if they're not equivalent, but you're right, it's not explicitly stated, which is odd. It's worth noting that `x != y` is defined as being equivalent to `!(x == y)` so that might force your hand here. – tadman Jul 18 '17 at 02:05

1 Answers1

3

"For input iterators, what are the requirements for comparing equality if one of the iterators has been invalidated?"

There are none. Quoting ISO/IEC 14882:2003(E), [lib.input.iterators],

== is an equivalence relation over its domain, (emphasis added)
bool(a==b) != bool(a!=b) over the domain of == (emphasis added)

And,

any copies of the previous value of r [prior to ++r] are no longer ... in the domain of ==.

There is no requirement that == or != have any particular behavior with respect to invalidated input iterators.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • To be clear, you are saying the standard does not define the behaviour of `x==y` in the question? – Yakk - Adam Nevraumont Jul 18 '17 at 02:39
  • So is the expression unspecified behaviour or undefined behaviour? – M.M Jul 18 '17 at 02:55
  • @M.M That would depend upon the precise type of `input_iter`. Since OP doesn't specify what `input_iter` is, other than it satisfies [lib.input.iterators], the behavior might be defined or it might not be. – Robᵩ Jul 18 '17 at 02:58