In C ++ member functions, a member function is called a common member function, for example, int get () const;
It is recorded in the encyclopedia that a common member function can only read the values of data members in the same class, but cannot be modified.
So what if it is modified? Of course we get a compilation error ....
What if I have to modify it? Then, mutable appears.
The mutable keyword is used to modify the value of a constant function.
Examples of mutable:
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;}
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;};