user4111232
user4111232

Reputation: 21

What makes these iterator comparisons undefined behavior?

In n3644 - Null Forward Iterators, it says:

The result of comparing a value-initialized iterator to an iterator with a non-singular value is undefined.

vector<int> v = {1,2,3};
auto ni = vector<int>::iterator();
auto nd = vector<double>::iterator();
ni == ni; // True.
nd != nd; // False.
v.begin() == ni; // Undefined behavior (likely false in practice).
v.end() == ni; // Undefined behavior (likely false in practice).
ni == nd; // Won’t compile.

Upvotes: 2

Views: 577

Answers (1)

user743382
user743382

Reputation:

You ask two very different questions. Your question about singular vs. non-singular is already answered here, so I will be ignoring that question, and only focusing on the question that isn't a duplicate.

Some containers may use special iterator values that look exactly like a default-constructed iterator value. For instance, iterators that do not have a valid pointer value for the iterator returned by end() may use their iterator type's equivalent of a null pointer to represent those.

Requiring the comparison to evaluate to true for those cases means that the implementation is forced to never change, even if a better approach for those iterator values is devised in the future.

Requiring the comparison to evaluate to false for those cases means that the implementation is forced to change.

Making the comparison undefined gives implementations the freedom they may need.

Xarn points out in the comments that it might have been a better choice to make the comparison give an unspecified result (either false or true, but no other options). That would have been a valid option, but the behaviour at the time of the proposal was already to disallow comparisons to iterators that do not come from the same containers (undefined behaviour, not unspecified results), and as far as I can tell, this proposal merely sought not to change anything that wasn't necessary, so left it as it was.

One valid argument for making it undefined rather than unspecified is that some implementations may want to provide special debugging iterators where invalid comparisons, that almost certainly are a programmer error, abort the program with a useful message.

Upvotes: 1

Related Questions