Horst Walter
Horst Walter

Reputation: 14081

Is comparing against singular iterator illegal?

If I understand the answer of "Why is comparing against "end()" iterator legal?" correctly, I can compare an end() iterator against a singular iterator. So we do it like here:

template <typename Iterator>
static bool isSingular(Iterator i) { return i == Iterator(); }

However, if this is called with an end() iterator I do get the following debug error (in a debug build -> map/set iterators incompatible). Is that error wrong, or is the code wrong and the error justified?


Win64 debug build error:

bool operator==(const _Tree_const_iterator& _Right) const
        {   // test for iterator equality
 #if _ITERATOR_DEBUG_LEVEL == 2
        if (this->_Getcont() != _Right._Getcont())
            {   // report error
            _DEBUG_ERROR("map/set iterators incompatible");
            }

Debugger

Upvotes: 2

Views: 892

Answers (2)

R Sahu
R Sahu

Reputation: 206627

If I understand the answer of "Why is comparing against "end()" iterator legal?" correctly, I can compare an end() iterator against a singular iterator.

That is incorrect understanding.

The iterator returned by std::vector::end() is not a singular iterator. It is associated with an instance of std::vector.

The standard states that:

Results of most expressions are undefined for singular values; the only exceptions are destroying an iterator that holds a singular value, the assignment of a non-singular value to an iterator that holds a singular value, and, for iterators that satisfy the DefaultConstructible requirements, using a value-initialized iterator as the source of a copy or move operation.

It does not specify explicitly whether comparing two singular iterators or a singular iterator with a non-singular iterator is incorrect or undefined behavior.

It obviously is not a problem for simple pointers but the standard leaves it open for compiler implementations to deal with comparing singular iterators with other iterators, singular or not, corresponding to the standard library containers.

In your case, the compiler does not allow it.

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385204

No answer on that other question claims that end() returns a singular iterator (it doesn't).

Regardless, in general, you can't compare anything to a singular iterator, not even another singular iterator! (though it may sometimes happen to appear to work).

Upvotes: 3

Related Questions