常成员函数和mutable的恩恩怨怨
在C++的成员函数中,有一种成员函数叫做常成员函数,形如:int get() const;
据百科中记载:常成员函数 含义 是通过该函数只能读取同一类中的数据成员的值,而不能修改它。
那么要是修改了呢?那当然得到的是一个编译错误。。。。
那我要是非要修改呢?这时,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;};