Comparing default-constructed iterators with operator==

c++, iterator, stl, visual-studio-2008

Solution

OK, I'll take a stab. The C++ Standard, Section 24.1/5:

Iterators can also have singular values that are not associated with any container. [Example: After the declaration of an uninitialized pointer x (as with int* x;), x must always be assumed to have a singular value of a pointer. ] Results of most expressions are undefined for singular values; the only excep- tion is an assignment of a non-singular value to an iterator that holds a singular value.

So, no, they can't be compared.

Problem

Does the C++ Standard say I should be able to compare two default-constructed STL iterators for equality? Are default-constructed iterators equality-comparable? I want the following, using std::list for example: ``` void foo(const std::list<int>::iterator iter) { if (iter == std::list<int>::iterator()) { // Something } } std::list<int>::iterator i; foo(i); ``` What I want here is something like a NULL value for iterators, but I'm not sure if it's legal. In the STL implementation included with Visual Studio 2008, they include assertions in std::list's operator==() that preclude this usage. (They check that each iterator is "owned" by the same container and default-constructed iterators have no container.) This would hint that it's not legal, or perhaps that they're being over-zealous.

Original source