Sunday, 15 June 2008

Mutable. Oh for goodness sake.

So, you have const, which declares things as being const, or at least immutable by you. An example is that a class API will often have functions declared as "this const":

void GetValue() const;

The trailing const refers to the this in the method (this is why you can't have const trailing global procedures or static methods).
Once in the method body, you'll find that you can acces the values but you can't modify them (they've all become const).

mutable lets you declare member variables as being not const even when the this is const. This sounds silly because you've just consted the class, and now you're unconsting members of the const this.

A really good examples of why this can be valid and useful is as a cache.

for example, in your special Library class, you have a method "int GetBookIDByName() const;". It gets the book ID of a book by looking through all the books it has and then returning true if the name matches. This is an expensive process, so, because the coder knows that the calling code is going to access the same book a few times, he stores the last book ID in a mutable, and then checks that first.

mutable int mLastBookID;

this allows him to quickly check to see if the book name is good, then saves the run through the whole library, but still allows the library to remain const because the caller isn't allowed to modify the library itself.

No comments: