mutable specifier | Mutable data member specifier |
storage-class-specifier := mutable
|
The mutable specifier can be used with the declaration of a data member. Using it means that the member can be modified even if the containing object is const.
// Represent a point in Cartesian coordinates. If the user requests polar // coordinates, compute and cache the polar coordinates. If the Cartesian // coordinates change, the polar coordinates must be recomputed. The polar // coordinates are computed only if they are needed. struct point { double angle( ) const { if (! has_angle_) { angle_ = tan2(y, x); has_angle_ = true; } return angle_; } void x(double x) { x_ = x; has_angle_ = has_arg_ = false; } ... private: double x_, y_; mutable double angle_, arg_; mutable bool has_angle_, has_arg_; }; int main( ) { const point pt(1, 2); std::cout << pt.angle( ); }
class, const, declaration, type, Chapter 6