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.
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.
- 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.
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.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With