The mutable
keyword in C++ is often used in scenarios where you want to allow certain class members to be modified, even when they are accessed through const
member functions. Here are some common use cases:
If you have a class that performs expensive calculations, you might want to cache the results to avoid recalculating. The cache variable can be marked as mutable
so it can be updated even in const
member functions.
#include <iostream>
class Calculator {
public:
int Calculate() const {
if (!cacheValid) {
cachedResult = PerformExpensiveCalculation();
cacheValid = true;
}
return cachedResult;
}
private:
int PerformExpensiveCalculation() const {
return 42; // Example calculation
}
mutable int cachedResult{0};
mutable bool cacheValid{false};
};
int main() {
Calculator calc;
std::cout << calc.Calculate() << '\n';
}
42
Sometimes you need to log data about method calls, such as how many times a method is called. These logging variables can be marked mutable
to allow modification from const
 methods.
#include <iostream>
class Logger {
public:
void Log() const {
++logCount;
std::cout << "Logging action #"
<< logCount << '\n';
}
private:
mutable int logCount{0};
};
int main() {
Logger logger;
logger.Log();
logger.Log();
}
Logging action #1
Logging action #2
In multi-threaded applications, you might use mutable
to allow modification of mutexes or other synchronization primitives inside const
member functions.
#include <iostream>
#include <mutex>
class ThreadSafeCounter {
public:
void Increment() const {
std::lock_guard<std::mutex> lock(mutex);
++count;
}
int GetCount() const {
std::lock_guard<std::mutex> lock(mutex);
return count;
}
private:
mutable int count{0};
mutable std::mutex mutex;
};
int main() {
ThreadSafeCounter counter;
counter.Increment();
std::cout << "Counter: " << counter.GetCount();
}
Counter: 1
Using mutable
helps maintain the logical constness of a class while allowing necessary internal modifications. However, it should be used sparingly to ensure it doesn't undermine the const correctness of your class design.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the mutable
keyword, which gives us more flexibility when working with const
objects.