提问者:小点点

Visual C关系运算符重载const正确性(使用std::排序)


在下面的示例代码中,重载运算符

#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;
}

Visual C在强制执行比较/关系运算符的const正确性时不符合标准吗?或者这与std::排序有关?


共1个答案

匿名用户

C标准指出,假设没有非常量函数将通过取消引用的迭代器应用,首先通过可以传递给sortCompare仿函数来声明它:

Compare是一种函数对象类型(20.8)。应用于Compare类型的对象的函数调用操作的返回值,当上下文转换为bool(4)时,如果调用的第一个参数小于第二个参数,则返回true,否则返回false。Comparecomp始终用于假设排序关系的算法。假设comp不会通过取消引用的迭代器应用任何非常量函数。

(强调我的)

然后,通过说明Compare运算符之间的关系

对于所有采用Compare的算法,有一个版本使用运算符

两个引用都来自。从25.4排序和相关操作。

因此,尽管没有明确说明成员运算符

我会说Visual C在这里有问题,因为它允许在取消引用的迭代器上调用非常量函数。

相关问题