What is the usage of ‘mutable’ in C++?
In C++, the mutable keyword is used to modify class member variables. Its purpose is to allow the value of that member variable to be changed in constant member functions.
By default, constant member functions (declared as const member functions) are not allowed to modify any member variables of a class as they are considered as read-only operations. However, there are situations where we may want to modify the value of a member variable within a constant member function, in such cases, we can use the mutable keyword.
Here is an example using the mutable keyword:
class Example {
private:
mutable int counter; // 可变的成员变量
public:
Example() : counter(0) {}
void increment() const {
counter++; // 在常量成员函数中修改成员变量的值
}
int getCounter() const {
return counter;
}
};
In the given example, counter is declared as mutable, allowing it to be modified in the constant member function increment(). Meanwhile, getCounter() is also a constant member function that only returns the value of counter without modifying it.
Using the “mutable” keyword should be done carefully as it breaks the read-only nature of constant member functions. It should only be used when it is necessary to modify specific member variables in constant member functions.