Original Post
🔒 Locked
Why/when to use mutable?
Advertisement
You use const member functions if you want to prevent them from changing data of an object. An example are getter functions, where you do not want them to modify the object. But what if the getter function should increment an "accessed counter " on the object ? Making the getter non-const introduces the posiibility to modify values of the object from the getter function. It is more safe to explicitly tell the compiler that the accessed counter may be modified even from a constant context:
class C { int value; mutable int accessed;public: int getValue() const { accessed++; return value; }};
Hi,
Pick up any (good) C++ textbook and it will read: be const correct.
This means that if a methods responsibility does not alter the state of the object, it should be const. This tightens the contract the class has to the outside world; ie. Get... () accessors must be const.
Sometimes you cannot perform that contract because you need to change your internal state. Then mutable is approriate for that member variable.
hth,
CipherCraft
Pick up any (good) C++ textbook and it will read: be const correct.
This means that if a methods responsibility does not alter the state of the object, it should be const. This tightens the contract the class has to the outside world; ie. Get... () accessors must be const.
Sometimes you cannot perform that contract because you need to change your internal state. Then mutable is approriate for that member variable.
hth,
CipherCraft
Anything you declare as mutable should only be part of the object's internal state, not its externally visible state, thus maintaining the semantics of const member functions. For instance, say you have some data structure that is searched often, and accesses come relatively close together (that is, if node n is accessed, you know that more than likely some node near n is going to be accessed next). So, you could store the last node accessed as a mutable variable, that is updated within a const member function (find(), or whatever). Thus, the internal state of the object is changed, but the user observes no external state change; the mutable variable is being used only as an optimization.
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement