What does a const mean by a member function?
There are two popular concepts: physical constants and logical constants.
C ++ defines Constants by using the concept of physical constants. That is, the const member function cannot change any non-static member variables in the object. For example:
1 class ctextblock 2 {3 Public: 4 ...... 5 STD: size_t length () const; 6 7 private: 8 char * ptext; 9 STD: size_t textlength; 10 bool lengthisvalid; 11}; 12 13 STD :: size_t ctextblock: length () const14 {15 if (! Lengthisvalid) 16 {17 textlength = STD: strlen (ptext); // The const member cannot be assigned to textlength and lengthisvalid18 lengthisvalid = true; 19} 20 return textlength; 21}
If an error occurs in the code above, the const Member cannot assign a value to textlength and lengthisvalid. How can this problem be solved?
The solution is simple: Use a const-related swing field of C ++: mutable.
Mutable releases the physical constant constraints of non-static member variables:
1 class ctextblock 2 {3 Public: 4 ...... 5 STD: size_t length () const; 6 7 private: 8 char * ptext; 9 mutable STD: size_t textlength; // These member variables may always be changed, even in the const member function, 10 mutable bool lengthisvalid; 11}; 12 13 STD: size_t ctextblock: length () const14 {15 if (! Lengthisvalid) 16 {17 textlength = STD: strlen (ptext); // now we can do this 18 lengthisvalid = true; 19} 20 return textlength; 21}