Explain C++ mutable in detail

  • 2020-11-03 22:32:15
  • OfStack

[

Code compilation environment: VS2017+Win32+Debug

]

mutalbe, which means "changeable" in Chinese, is the opposite of constant (const in C++). In C++, mutable is also set to break the limit of const, and the variable modified by mutable will always be in a variable state.

mutable serves two purposes:

(1) In the case that most of the data members in the constant object are still "read-only", the modification of individual data members is implemented;
(2) Enable the const function of the class to modify the mutable data members of the object.

Tips for using mutable:

(1) mutable can only operate on non-static and non-trivial data members of the class.
(2) In one class, mutable should be used or not used as much as possible, as the extensive use of mutable indicates that the program design has defects.

The sample code is as follows:


#include <iostream>
using namespace std;

//mutable int test;// Compile error 

class Student
{
	string name;
	mutable int getNum;
	//mutable const int test;  // Compile error 
	//mutable static int static1;// Compile error 
public:
	Student(char* name)
	{
		this->name=name;
		getNum=0;
	}
	string getName() const
	{
		++getNum;
		return name;
	}
	void pintTimes() const
	{
		cout<<getNum<<endl;
	}
};

int main(int argc, char* argv[])
{
	const Student s(" zhang 3");
	cout<<s.getName().c_str()<<endl;
	s.pintTimes();
	return 0;
}

Program output results:

[

3
1

]

mutable cannot modify const data members are easy to understand, because mutable and const are originally antisense, while the modification is not contradictory. mutable cannot modify static data members, members because static data stored in the Data BSS section, or paragraph belongs to the class, do not belong to the class object, so often objects and often function can be arbitrarily modify, so static data members of a class does not need mutable modification, but for the object's data member is not often can be modified, if want to change, you will need to mutable modification. The sample code is as follows:


#include <iostream>
using namespace std;

class Student
{
	string name;	
public:
	static int test1;
	void modify() const
	{
		test1=15;
		cout<<test1<<endl;
	}
};

int Student::test1;// statement test1 It is initialized to the default value of the compiler 
int main(int argc, char* argv[])
{
	const Student s(" zhang 3");
	s.test1=5;// A constant object can modify the data members of a static class test1
	cout<<Student::test1<<endl;
	s. modify();// Constant function modification 
	return 0;
}

The output result of the program is:

[

5
15

]

The above is a detailed explanation of the use of mutable in C++. For more information about C++ mutable, please follow other related articles on this site!


Related articles: