为什么在为 STL 定义函子时必须使用 const& 参数?

Why must I use a const& parameter when defining a functor for STL?

本文关键字:const 参数 STL 定义 为什么      更新时间:2023-10-16
auto cmp = [](pair<int, int> & left, pair<int, int> & right){if(left > right) return true; else return false;};
multiset<pair<int, int>, decltype(cmp)> mt(cmp);
// If I just compile the two lines above, it will work.
// But if I try to insert some elements as below, I'll get errors.
//mt.insert({0, 3});
//mt.insert({1, 1});

但是,如果我为cmp的两个参数添加const或删除&,它将工作。

当我试图将元素插入mt时,为什么我不能使用cmp的非const引用?

根据cppreference, cmp必须满足Compare的要求。

Compare的引用说:

与任何BinaryPredicate一样,该表达式的求值不允许调用解引用迭代器的非const成员函数。

为了防止比较器意外地改变存储元素的状态,您需要使用const引用或通过复制获取值。

编译器认为您可能会更改传递给cmp函数的参数,因为您已经指定了输入参数的引用。然而,insert语句传递的是不能修改的常量(编译器知道这一点)。因此不匹配。

如果你分配两个变量,然后将变量传递给你的insert()调用,它工作吗?