mutable关键词的作用:被它修饰的成员变量,即使在常函数中也可以被更改。
mutable适用场合主要有以下两种,使用前要三思。
- 有一个常量成员函数,但是出于调试目的,想要跟踪常函数被调用的次数。注意如果你正在考虑使用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; };
只有pi()第一次被访问时才计算pi的值,计算出pi的值后,就保存起来,并且这个值是固定的,这样对于需要大量计算得出一个固定值的操作,就只需执行一次,而逻辑上这个函数依然是常函数。