I can talk with some authorities on this, as I am the one who wrote this code.
Here is the comparison that is validated in your example:
https://github.com/llvm-mirror/libcxx/blob/master/include/algorithm#L3994-L3995
As the link becomes obsolete over time (point to an invalid line), I will also quote the code here:
// __m still guards upward moving __i while (__comp(*__i, *__m)) ++__i;
This is called an βunguardedβ loop because there is no verification that the __i iterator completes the end of the sequence as it __i . The reason for this is that the invariant of this algorithm is that at this point it is known that __i <= __m (which is also in the comment 3 lines above this quote).
If you look at the code above this quote, you will see the following comments:
So, before we get to this point, a secure search by sequence is performed. That is, this test:
if (__i == --__j)
After this test detects a lower guard, the algorithm then proceeds to insecure loops that have only one iteration test, whereas otherwise there would be two iteration tests (an iterator test and an iterated value dereferenced test).
The use of "unguarded loops" is the reason that the element is compared with itself. During development, I measured that the cost of one additional comparison in a loop was better than including two comparisons per iteration in a loop.
Of course, this is an engineering compromise. If the comparison function were terribly expensive compared to the cost of comparing the iterators themselves, one could come to a different conclusion.
This answer is fully consistent with rici answer , which is also correct (and I supported it). I added my voice, as I could discard "presumably" and point to certain lines of code in the algorithm.