C++ “const” keyword explanation

前端 未结 8 1961
半阙折子戏
半阙折子戏 2020-12-24 12:58

When reading tutorials and code written in C++, I often stumble over the const keyword.

I see that it is used like the following:

const          


        
8条回答
  •  星月不相逢
    2020-12-24 13:14

    void myfunc(const char x);
    

    This means that the parameter x is a char whose value cannot be changed inside the function. For example:

    void myfunc(const char x)
    {
      char y = x;  // OK
      x = y;       // failure - x is `const`
    }
    

    For the last one:

    int myfunc() const;
    

    This is illegal unless it's inside a class declaration - const member functions prevent modification of any class member - const nonmember functions cannot be used. in this case the definition would be something like:

    int myclass::myfunc() const
    {
      // do stuff that leaves members unchanged
    }
    

    If you have specific class members that need to be modifiable in const member functions, you can declare them mutable. An example would be a member lock_guard that makes the class's const and non-const member functions threadsafe, but must change during its own internal operation.

提交回复
热议问题