Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

A while ago I came across some code that marked a member variable of a class with the mutable keyword. As far as I can see it simply allows you to modify a variable in a const method:

class Foo   {   private:       mutable bool done_;   public:       void doSomething() const { ...; done_ = true; }   }; 

Is this the only use of this keyword or is there more to it than meets the eye? I have since used this technique in a class, marking a boost::mutex as mutable allowing const functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.

like image 346
Rob Avatar asked Sep 19 '08 19:09

Rob


People also ask

What is the purpose of mutable keyword?

The keyword mutable is mainly used to allow a particular data member of const object to be modified. When we declare a function as const, the this pointer passed to function becomes const. Adding mutable to a variable allows a const pointer to change members.

What is the purpose of mutable keyword Mcq?

- The mutable keyword allows the data member of a class to change within a const member function. - It allows to assign the values to a data member belonging to a class defined as “Const” or constant. - It allows a const pointer to change members.

What is the use of mutable in C++?

The mutable storage class specifier is used only on a class data member to make it modifiable even though the member is part of an object declared as const . You cannot use the mutable specifier with names declared as static or const , or reference members.

What is difference between volatile and mutable in C++?

A variable marked mutable allows for it to be modified in a method declared const . A variable marked volatile tells the compiler that it must read/write the variable every time your code tells it too (i.e. it cant optimize away accesses to the variable).


1 Answers

It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result.

Since c++11 mutable can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):

int x = 0; auto f1 = [=]() mutable {x = 42;};  // OK auto f2 = [=]()         {x = 42;};  // Error: a by-value capture cannot be modified in a non-mutable lambda 
like image 96
KeithB Avatar answered Sep 19 '22 04:09

KeithB