一、含义
mutable “可变的”、“易变的”,与const相反
二、作用
突破const限制,被const修饰的变量,将永远处于可变的状态,即使在一个const函数中。如果让类的成员函数不改变对象的状态,一般这个成员函数会声明成const,但是如果需要在const函数中修改一些跟类无关的数据成员,那么这个数据成员就应该被mutable修饰。
三、示例
#include <iostream>
using namespace std;
class TestMutable
{
public:
TestMutable();
void Output() const;
int GetCnt() const;
private:
mutable int myCnt;
};
TestMutable::TestMutable():myCnt(0)
{
}
void TestMutable::Output() const
{
cout << "Output for test!" << endl;
myCnt += 2;
}
int TestMutable::GetCnt() const
{
return myCnt;
}
int main()
{
TestMutable test;
test.Output();
cout << "cnt:" << test.GetCnt() << endl;
return 0;
}
TestMutable类中有一个输出函数,不会修改类的状态,所以被声明为const的。 如果要增添一个功能:统计每个对象调用输出函数Output()的次数。如果用来计数的变量是普通的变量的话,那么在const成员函数Output里面是不能修改该变量的值的;而该变量跟对象的状态无关,所以应该为了修改该变量而去掉Output的const属性。这个时候,就该我们的mutable出场了——只要用mutalbe来修饰这个变量,所有问题就迎刃而解了。
计数器myCnt 被mutable修饰,那么它就可以突破const的限制,在被const修饰的函数里面也能被修改。