The Chinese meaning of Mutalbe is "mutable, variable", which is the opposite of Const in C + +. In C + +, mutable is also set to break the limits of Const. Variables that are 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 this member function is generally declared as Const. However, there are times when we need to modify some data members that are unrelated to the class state in the Const function, then this data member should be mutalbe.
Here is a small example:
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 for output, which invokes the output method of the object LX, in order to prevent calls to other member functions in the function to modify any member variables, so the parameters are also const decorated.
If now, let's add a function: Calculate the number of outputs per object. If the variable used to count 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 state of the object, so the const property of the output should be removed in order to modify the variable. At this point, it's time for our mutable to play-just use Mutalbe to modify the variable, and all the problems will be solved.
The following is the modified code:
Header file
Filename:testmutable.h#include <iostream>using namespace Std;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++;} void outputtest (const clxtest& lx) {lx. Output ();} int clxtest::getoutputtimes () Const{return m_itimes;}
Implementation file
Filename:testmutable.cpp#include "testMutable.h" int main () {clxtest clx;clx. Output (); Outputtest (CLX);cout<< "times =" << clx. Getoutputtimes () << Endl; System ("Pause");}
Execution results on Visual Studio 2010
The counter m_itimes is modified by mutable, so it can break through the const limit and can be modified in the const-modified function.
In-depth understanding of mutable keywords in C + +