Mutable storage class specifier

mutable is the one of the storage specifier in C++.
In general, const function does not allow to modify data members of an object who called it. However, with the help of mutable specifier, we can achieve it.
Simple example shows use of mutable specifier.

#include <iostream>
using namespace std;
class base {
unsigned int m_int;
mutable unsigned int m_mutableInt;
public:
base(unsigned int x, unsigned int y) {
m_int = x;
m_mutableInt = y;
}
void read() const { //const function
m_int = 40; // Error: This is not allowed.
m_mutableInt = 10; // mutable data member can be changed in const function.
cout << “m_int and m_mutableInt” << m_int << “ “ << m_mutableInt << endl;
}
};

int main() {
base b(20,30);
b.read();
return 0;
}
  • mutable specifier cannot be used with static data members of a class because static function cannot be const and const member functions can change non-const static member. Similarly, mutable specifier cannot be used for const and reference data member of a class.
  • There are some real life scenarios in the programming world where we need mutable data member.
  • Consider in a multithreaded application, we have a data member of a class, which can be read by multiple threads. There is a const function, which return this data member value, need to synchronize so that thread can read its consistent value. For that, we need synchronization mechanism so that only one thread can read its value at a time. Mutex is one of the synchronization technique. In order for mutex to work in const function, it has to be mutable otherwise compiler will throw an error.


Related posts