When should a member function have a const qualifier and when shouldn't it?

后端 未结 6 1305
轻奢々
轻奢々 2021-02-06 09:04

About six years ago, a software engineer named Harri Porten wrote this article, asking the question, \"When should a member function have a const qualifier and when shouldn\'t i

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 09:30

    I personally use a very simple Rule Of Thumb:

    If the observable state of an object does not change when calling a given method, this method ought to be const.

    In general it is similar to the rule mentioned by SCFrench about Equality Comparison, except that most of my classes cannot be compared.

    I would like to push the debate one step further though:

    When requiring an argument, a function ought to take it by const handle (or copy) if the argument is left unchanged (for an external observer)

    It is slightly more general, since after all the method of a class is nothing else than a free-standing function accepting an instance of the class as a first argument:

    class Foo { void bar() const; };
    

    is equivalent to:

    class Foo { friend void bar(const Foo& self); }; // ALA Python
    

提交回复
热议问题