Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use operator< on 'std::deque'?

Ran cppcheck on my code base and received the following error:

Dangerous iterator comparison using operator< on 'std::deque'.

But a deque's iterator is a random access iterator, and random access iterators support inequality operators. So what gives?

Example:

#include <deque>

int main()
{
    std::deque<int> d;
    std::deque<int>::iterator di1 = d.begin();
    std::deque<int>::iterator di2 = d.end();

    if (di1 < di2)
    {
        // (error) Dangerous iterator comparison using operator< on 'std::deque'.
    }

    return 0;
}

Edit: This bug was submitted and fixed via cppcheck ticket #5926.

like image 947
Evan Rose Avatar asked Jun 16 '14 15:06

Evan Rose


1 Answers

It's a bug in cppcheck.

If we look at the code for the rule stlBoundaries(), the containers it triggers on are:

"bitset|deque|list|forward_list|map|multimap|multiset|priority_queue|queue|set|stack|hash_map|hash_multimap|hash_set|unordered_map|unordered_multimap|unordered_set|unordered_multiset"

However, in addition to deque, priority_queue is also guaranteed to have random access iterators.

The rationale for this rule is that programmers might accidentally write:

for (auto it = container.begin(); it < container.end(); ++it)
    ...

by analogy with the equivalent integer-indexed for loop, and this might actually compile for non-random-access iterators with some sort of conversion to pointer.

This is the original trac item that added the rule: http://sourceforge.net/apps/trac/cppcheck/ticket/247 and this ticket exempted vector: http://sourceforge.net/apps/trac/cppcheck/ticket/313

like image 114
ecatmur Avatar answered Sep 22 '22 07:09

ecatmur