|
Page 6 of 6 mutable Class Members We discussed const members earlier and like many things there are exceptions to the rule -- in this case the mutable keyword is the key to making exceptions to const-ness. There are a number of possible uses of the mutable keyword, but most of them are obscure and rarely used. The most often usage of mutable is to specifically declare that a class member variable may be changed by a const method. This is most often used in cases such as delayed initialization or similar. Take for example: class Foo { public: Foo() : m_object( 0 ) // initalize to null {
} ~Foo() { delete m_object; }
const Object *object() const { if( !m_object ) m_object = new Object;
return m_object; }
private: mutable Object *m_object; }; In the example above we have an accessor which convention says should be const. However in this case we're assuming that we never want to return an uninitialized value, so because the member variable has been marked as being mutable we're able to modify it even in a const method. If m_object were not marked as mutable then the compiler would give an error indicating that we are not allowed to change the value of a class member variable in a const method. Note: Like exceptions to most rules, the mutable keyword exists for a reason, but should not be overused. If you find that you have marked a significant number of the member variables in your class as mutable you should probably consider whether or not the design really makes sense.
|