Meaning of 'const' last in a function declaration of a class?

后端 未结 10 2369
无人共我
无人共我 2020-11-21 06:37

What is the meaning of const in declarations like these? The const confuses me.

class foobar
{
  public:
     operator int () const         


        
10条回答
  •  清歌不尽
    2020-11-21 07:16

    https://isocpp.org/wiki/faq/const-correctness#const-member-fns

    What is a "const member function"?

    A member function that inspects (rather than mutates) its object.

    A const member function is indicated by a const suffix just after the member function’s parameter list. Member functions with a const suffix are called “const member functions” or “inspectors.” Member functions without a const suffix are called “non-const member functions” or “mutators.”

    class Fred {
    public:
      void inspect() const;   // This member promises NOT to change *this
      void mutate();          // This member function might change *this
    };
    void userCode(Fred& changeable, const Fred& unchangeable)
    {
      changeable.inspect();   // Okay: doesn't change a changeable object
      changeable.mutate();    // Okay: changes a changeable object
      unchangeable.inspect(); // Okay: doesn't change an unchangeable object
      unchangeable.mutate();  // ERROR: attempt to change unchangeable object
    }
    

    The attempt to call unchangeable.mutate() is an error caught at compile time. There is no runtime space or speed penalty for const, and you don’t need to write test-cases to check it at runtime.

    The trailing const on inspect() member function should be used to mean the method won’t change the object’s abstract (client-visible) state. That is slightly different from saying the method won’t change the “raw bits” of the object’s struct. C++ compilers aren’t allowed to take the “bitwise” interpretation unless they can solve the aliasing problem, which normally can’t be solved (i.e., a non-const alias could exist which could modify the state of the object). Another (important) insight from this aliasing issue: pointing at an object with a pointer-to-const doesn’t guarantee that the object won’t change; it merely promises that the object won’t change via that pointer.

提交回复
热议问题