Skip to main content
gamedev.net
🔒 Locked

Why/when to use mutable?

Started by Ilankt 5 replies 950+ views
Original Post
Ilankt
Ilankt
I just dont get it why to use mutable, if you want to change the values of the class, just dont use const... can you explain me when you need to use it?
How appropriate, you fight like a cow!
nmi
nmi
From within a const member function, you can change data that is explicitly marked as mutable.

class C{	mutable int i;public:	int func() const { i = 3; }};int main(){	C c;	c.func();	return 0;}


If you remove the mutable keyword, it won't compile anymore.
Ilankt
Ilankt
nmi, Thanks, but I know what is mutable, I just dont understand why just not making "func" non const if you are going to change *this....
How appropriate, you fight like a cow!
nmi
nmi
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;  }};

CipherCraft
CipherCraft
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
Ilankt
Ilankt
CipherCraft, I'm trying to be "const correct" this is why I'm asking.
nmi, thanks, I think it make sense for me now.
How appropriate, you fight like a cow!
Desert Fox
Desert Fox
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.
"Is life so dear, or peace so sweet, as to be purchased at the price of chains and slavery?" - Patrick Henry

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.