1.概念
被mutable修饰的变量,处于可变的状态,即使在一个被const修饰的函数中。
2. 代码示例
class A
{
public:
A(){}
int GetValue() const;
private:
mutable int index = 1;
};
//被const修饰的成员函数,不允许修改成员变量,但是如果成员变量被mutable修饰,则可以修改,下面代码编译通过
int A::GetValue() const
{
index++;
return index;
}
int main()
{
A a;
cout << a.GetValue() << endl;
system("pause");
return 0;
}
3. 存在的必要性
mutable的意思是"这个成员变量不算对象内部的状态"
比如调试时,某一变量用来计算const成员函数被调用的次数,此时可声明为mutable。