为什么重载的"运算符<"应该是类的常量?
Why overloaded ' operator < ' should be const for class?
有谁能在STL sort
算法的背景下解释这种行为吗?如果operator <
未定义const
,则给出错误,
error: passing ‘const B’ as ‘this’ argument of ‘bool B::operator<(const B&)’ discards qualifiers [-fpermissive]
while (__pivot < *__last)
是sort
算法是const
对象还是sort
是const
方法?
class B
{
public:
...
bool operator < (const B& b) const // why const required here?
{
return (m_i < b.m_i);
}
...
private:
int m_i;
int m_j;
};
int main()
{
vector<B> Bvec2 {B(5), B(3), B(30), B(20), B(8)};
std::sort(Bvec2.begin(), Bvec2.end());
...
}
将函数标记为const保证它不会改变对象。因此,它可以用于const对象。
STL几乎肯定将实参作为const,因为这样做是明智的。
将operator<
定义为const应该没有什么害处,因为我无法想象有一个小于操作符来改变对象。那就太傻了。
如果您想知道在Fedora 20机器上从libstdc++ bits/stl_algorithm .h中复制的代码的确切位置:
/// This is a helper function...
template<typename _RandomAccessIterator, typename _Tp, typename _Compare>
_RandomAccessIterator
__unguarded_partition(_RandomAccessIterator __first,
_RandomAccessIterator __last,
const _Tp& __pivot, _Compare __comp)
const _Tp& __pivot
,就在这里
标准对此有一点不清楚,但是[alg.sorting]
给出了两个提示,说明为什么编译失败可能是符合标准的行为。第一个是[alg.sorting]/2
:
…假定
comp
不会通过解引用迭代器应用任何非常数函数。
接下来,我们被告知当没有提供比较器时,[alg.sorting]/3
:
…
comp(*i, *j) != false
默认为*i < *j != false
,因为在您的例子中,comp
默认为*i < *j != false
,这将非const函数应用于解引用迭代器。这使[alg.sorting]/2
中给出的假设无效,因此您的代码具有未定义的行为。具有未定义行为的代码不编译是合法的。
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 呼叫运营商<<临时
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 为什么我可以通过引用修改常量返回
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何创建长度由常量参数指定的数组
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?