The Chinese meaning of mutalbe is "variable, easy to change", which is the opposite of constant (const in both C ++.
In C ++, mutable is also set to break through the const restrictions. Variables modified by mutable will always be in a mutable state, even in a const function.
We know that if the member function of the class does not change the state of the object, the member function will be declared as Const. However, sometimes we need to modify some data members irrelevant to the class status in the const function, so this data member should be modified by mutalbe.
Below 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 output function of the clxtest member function is used for output and does not modify the status of the class. Therefore, it is declared as Const.
The outputtest function is also used for output. It calls the output method of the object lx. To prevent other member functions from being called to modify any member variables, the parameter is also modified by const.
Now, we need to add a function: calculate the number of output times of each object. If the variable used for counting is a common variable, the value of the variable cannot be modified in the output of the const member function. The variable has nothing to do with the state of the object, therefore, the const attribute of output should be removed to modify the variable. At this time, our mutable will be available-as long as mutalbe is used to modify this variable, all the problems will be solved.
The modified code is 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 m_itimes counter is mutable, so it can break through the const limitation and be modified in the function modified by const.
From: http://dev.yesky.com/393/3007393.shtml