The mutable keyword of Bill's second season of C ++ Learning
0. Reasons for the article
I plan to systematically organize the basic knowledge while reading the book, so that everyone can conveniently read the book. The collected knowledge should be referenced in books as much as possible, which is more reliable than the materials obtained on the Internet.
I. Role
Mutable is used to solve the problem that data members of objects cannot be modified in common functions.
In some cases, if you want to modify the value of a member variable in a constant function, add mutable before the variable. When the majority of data members of a constant object are still "read-only", modifications can be made to individual members.
# Include
# Include
Using namespace std; class Student {string Name; // The default value is private int times_of_getname; public: Student (char * name): Name (name), times_of_getname (0) {} string get_name () {times_of_getname ++; return Name;} void PrintTimes () const {cout <
The above program will report an error because the constant object s (student entity whose information cannot be modified) calls the non-const function get_name (), but if you change get_name () to const, times_of_getname cannot be modified.
However, if it is changed:
mutable int times_of_getname;string get_name() const{}
You can.
Ii. Precautions
Note the following when using the keyword mutable:
(1) mutable is only used for non-static and non-constant data members of the class.
(2) the mutable keyword prompts the compiler that the variable can be modified by the const function of the class.
(3) In a class, variables modified with mutable can only be a minority, or are not used at all. A large amount of use represents defects in programming.
References
[1] Chen Gang. C ++ advanced tutorial [M]. Wuhan: Wuhan University Press, 2008.