简体   繁体   中英

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM