The Chinese meaning of Mutalbe is "changeable, variable" and is the antonym of constant (const in C + +).
In C + +, mutable is also set to break the const limit. Variables modified by mutable will always be in a mutable state, even in a const function.
We know that if the member function of a class does not change the state of the object, then the member function is generally declared as Const. However, sometimes we need to modify some data members that are not related to the class state in the Const function, so the data member should be mutalbe.
Here is a small example:
Copy Code code as follows:
Class Clxtest
{
Public
void Output () const;
};
void Clxtest::output () const
{
cout << "Output for test!" << Endl;
}
void outputtest (const clxtest& LX)
{
Lx. Output ();
}
The member function output of the class clxtest is used for outputting and does not modify the state of the class, so it is declared as Const.
Function outputtest is also used to output, which calls the object LX output method, in order to prevent the call to other member functions in the function to modify any member variables, so the parameters are also modified by the Const.
Now, we're going to add a feature that calculates the number of outputs per object. If the variable used for counting is a normal variable, then the value of the variable cannot be modified in the const member function output, and the variable is independent of the object's state, so the const attribute of output should be removed to modify the variable. At this point, it's time for our mutable to come out-just use mutalbe to decorate the variable, and all the problems will be solved.
Here is the modified code:
Copy Code code as follows:
Class Clxtest
{
Public
Clxtest ();
~clxtest ();
void Output () const;
int getoutputtimes () const;
Private
mutable int m_itimes;
};
Clxtest::clxtest ()
{
M_itimes = 0;
}
Clxtest::~clxtest ()
{}
void Clxtest::output () const
{
cout << "Output for test!" << Endl;
m_itimes++;
}
int Clxtest::getoutputtimes () const
{
return m_itimes;
}
void outputtest (const clxtest& LX)
{
cout << LX. Getoutputtimes () << Endl;
Lx. Output ();
cout << LX. Getoutputtimes () << Endl;
}
The counter m_itimes is mutable modified, then it can break the const limit and can be modified in the const-modified function.