Mutable keywords: member variables modified by mutable can be changed even in common functions.
Mutable can be used in the following scenarios. Think twice before use.
- There is a constant member function, but for debugging purposes, you want to track the number of calls of a constant function. Note that if you are considering using the mutable variable, it will violate the constant semantics, so please think twice.
Class employee {public: employee (const STD: string & name): _ name (name), _ access_count (0) {} void set_name (const STD: string & name) {_ name = Name;} STD: String get_name () const {_ access_count ++; return _ name;} int get_access_count () const {return _ access_count;} PRIVATE: STD: String _ name; mutable int _ access_count ;}
- A more complex example may sometimes require caching the results of a complex operation.
Class mathobject {public: mathobject (): pi_cached (false) {} double Pi () const {If (! Pi_cached) {/* This is an insanely slow way to calculate pi. */PI = 4; for (long step = 3; Step <1000000000; Step + = 4) {PI + = (-4.0/(double) Step) + (4.0/(double) Step + 2);} pi_cached = true;} return PI;} PRIVATE: mutable bool pi_cached; mutable double PI ;};
The pI value is calculated only when Pi () is accessed for the first time. After the PI value is calculated, it is saved and the value is fixed, in this way, you only need to execute an operation that requires a large amount of computing to get a fixed value, and the logic of this function is still a constant function.