Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

c++ - Why overloaded ' operator < ' should be const for class?

Can anybody explain this behavior in context of STL sort algorithm? If operator < is not defined const it gives error,

error: passing ‘const B’ as ‘this’ argument of ‘bool B::operator<(const B&)’ discards qualifiers [-fpermissive] while (__pivot < *__last)

Is sort algo lhs const object or sort is const method?

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());
  ...
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Marking the function as const promises that it will not change the object. So it can be used on const objects.

The STL almost certainly takes the arguments as const, because that is the smart thing to do.

It shouldn't hurt you to define operator< as const because I cannot imagine having a less-than operator that changes the object. That would just be silly.

If you want to know exactly where here is some code copied out of libstdc++ bits/stl_algo.h on a Fedora 20 machine:

  /// 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, right there.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...