What does ‘mutable’ mean in C++?

In C++, the keyword mutable is used to modify class member variables. It means that member variables marked as mutable can be modified in const member functions.

In general, const member functions are not allowed to modify object member variables. However, in special cases, there may be a need to modify the value of a member variable in a const member function. In such cases, the mutable keyword can be used to mark the member variable, allowing it to be modified in a const member function.

Modifying member variables declared with the mutable keyword within const member functions is allowed in order to protect the object’s immutability while still permitting specific variables to be altered in const member functions.

Here is an example demonstrating the use of the mutable keyword:

class MyClass {
public:
  void setValue(int value) const {
    // 修改被 mutable 修饰的成员变量
    mutableValue = value;
  }

  int getValue() const {
    // const 成员函数可以访问和读取 mutable 成员变量
    return mutableValue;
  }

private:
  mutable int mutableValue;
};

In the above example, mutableValue is a member variable with mutable qualifier. setValue is a const member function that can modify the value of mutableValue. On the other hand, getValue is another const member function that can only read the value of mutableValue and cannot modify it.

It is important to note that the mutable keyword can only be used for non-static member variables, not for static member variables or global variables.

bannerAds