Junior — Middle
Explain the purpose and use of the keyword mutable in programming.
sobes.tech AI
Answer from AI
In C++, the keyword mutable is used to denote class members that can be modified even in const objects or methods.
Typically, if an object is declared as const, its fields cannot be modified within methods declared as const. But if a field is marked as mutable, it can be changed even under these conditions.
This is useful for implementing caching, statistics counting, or other auxiliary data that logically does not change the state of the object.
Example:
class Example {
mutable int cache;
public:
Example() : cache(0) {}
int getValue() const {
if (cache == 0) {
// compute the value and store it in cache
cache = 42;
}
return cache;
}
};
Here, cache can be modified inside the const method getValue thanks to mutable.