In depth analysis the mutable keyword in c + +

  • 2020-04-02 01:53:09
  • OfStack

Mutalbe means "variable" in Chinese and is the opposite of constant (const in C++).

In c + +, mutable is also set to breakthrough the limitation of const. Is decorated mutable variables that will forever is in a state of a variable, even in a const function.

We know that if a member function of a class does not change the state of the object, then the member function is generally declared const. However, sometimes we need to modify some data member that is not related to the class state in the const function, then the data member should be modified by mutalbe.

Here's 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 Output of the ClxTest class is used for Output and does not modify the state of the class, so it is declared const.

The function OutputTest is also used for Output, in which the Output Output method of object lx is called. In order to prevent calling other member functions in the function to modify any member variables, the parameters are also modified by const.

Now, let's add a new feature: count the number of outputs per object. If the variable used for counting is a normal variable, then the value of the variable cannot be changed in the Output of the const member function. This variable is independent of the state of the object, so the Output const attribute should be removed in order to modify the variable. This time, it played the mutable - as long as we use mutalbe to modify the variable, all problems are solved.

Here is the modified code:


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;
}

Counter m_iTimes is mutable, then it can breakthrough the limitation of const, inside is decorated const function can also be modified.


Related articles: