문제

In the example code below, the overloaded operator< was not const qualified, and it compiles under Visual C++ (all versions up to 2013 Preview), but under Clang, it throws an error - note: candidate function not viable: 'this' argument has type 'const Entry', but method is not marked const bool operator<( const Entry& other ).

#include "stdafx.h"
#include <vector>
#include <algorithm>

struct Entry
{
    unsigned int age;
    bool operator<( const Entry& other ) // !!! no const qualification here !!!
    {
        return age < other.age;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    std::vector<Entry> entries;
    for( unsigned int i = 0; i < 100; ++i )
    {
        Entry entry;
        entry.age = i;
        entries.push_back( entry );
    }
    // Sort by age
    std::sort( entries.begin(), entries.end() );
    return 0;
}

Is Visual C++ not standard conforming in enforcing the const-correctness of the comparison/relational operators? Or this is something to do with std::sort?

도움이 되었습니까?

해결책

The C++ standard states that it is assumed that no non-constant function will be applied via the dereferenced iterators, first by stating it in terms of the Compare functor that can be passed to sort:

Compare is a function object type (20.8). The return value of the function call operation applied to an object of type Compare, when contextually converted to bool (4), yields true if the first argument of the call is less than the second, and false otherwise. Compare comp is used throughout for algorithms assuming an ordering relation. It is assumed that comp will not apply any non-constant function through the dereferenced iterator.

(emphasis mine)

and then, by stating the relation between Compare and operator<:

For all algorithms that take Compare, there is a version that uses operator< instead. That is, comp(*i, *j) != false defaults to *i < *j != false. For algorithms other than those described in 25.4.3 to work correctly, comp has to induce a strict weak ordering on the values.

Both quotes from . From 25.4 Sorting and related operations.

So, although it is not explicitly stated that a member operator< has to be const, the assumption that it is means it must be. It would not make sense to place restrictions on comp and not on operator<.

I would say Visual C++ is at fault here since it allows for non-const functions to be called on the dereferenced iterators.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top