In C++,mutable
It is a rare but very useful keyword. Its function may be less intuitive, but it can provide great flexibility in specific scenarios, especially when it comes to constant member functions, thread synchronization, and object state modifications. understandmutable
How it works and its usage scenarios are very important for C++ developers.
1. Basic concepts of mutable keywords
mutable
is a member variable modifier that allows us toConstant member functionsModify specific member variables in . Normally, constant member functions do not allow modification of any member variables of a class because they are marked "immutable". However, usemutable
Modified member variables can be modified even in constant member functions.
2. The role of mutable
Constant member functions in normal cases:
In C++, when we declare a member function as a constant (i.e. add at the end of the function declarationconst
), which means we promise that the function will not modify any non-static member variables of the class. For example:
class MyClass { public: int value; void setValue(int v) const { // Constant member functions value = v; // Error: Cannot modify value in constant member function } };
In the above code,setValue
is a constant member function that attempts to modifyvalue
Member variables can cause compilation errors.
usemutable
Situation:
When we usemutable
When a keyword modifies a member variable, this specific member variable can be modified even in a constant member function.
#include <iostream> using namespace std; class MyClass { public: mutable int value; // Use mutable to modify MyClass(int v) : value(v) {} void setValue(int v) const { // Constant member functions value = v; // Allow to modify value } void printValue() const { cout << "Value: " << value << endl; } }; int main() { MyClass obj(10); (); // Output: Value: 10 (20); // Modify the value in the constant member function (); // Output: Value: 20 return 0; }
Output:
Value: 10
Value: 20
explain:
-
value
It's onemutable
Member variables, so even insetValue
It can also be modified in such a constant member function. - Constant member functions
setValue
The member variable of the object should not be modified, but becausevalue
quiltmutable
Modification, the compiler allows modification in this functionvalue
。
3. Common usage scenarios of mutable
3.1 Implementing the caching mechanism
mutable
Keywords are often used to implement caching mechanisms. In some cases, some member variables of a class need to be calculated based on the values of other members and cached the results. Even if the methods of this class are constant, we still want to be able to modify the cached data.
For example, consider a scenario where complex computation results are cached:
#include <iostream> using namespace std; class ExpensiveCalculation { private: mutable int cachedResult; // Cache calculation results mutable bool isCacheValid; // Is the cache valid?public: ExpensiveCalculation() : cachedResult(0), isCacheValid(false) {} // A constant member function to return cached calculation results int getResult() const { if (!isCacheValid) { // If the cache is invalid, expensive calculations are performed cachedResult = performComplexCalculation(); isCacheValid = true; } return cachedResult; } // Suppose this is a complex computing process int performComplexCalculation() const { cout << "Performing complex calculation..." << endl; return 42; // Here is just a simple example } }; int main() { ExpensiveCalculation obj; cout << "First result: " << () << endl; // Will trigger complex calculations cout << "Second result: " << () << endl; // Use cache, no longer calculate return 0; }
Output:
Performing complex calculation...
First result: 42
Second result: 42
explain:
- exist
getResult
In a constant member function,cachedResult
andisCacheValid
quiltmutable
Modifications, so they can be modified even in constant functions. This allows us to update the cache without changing other states of the object. -
performComplexCalculation
It is executed only when the cache is invalid, reducing the overhead of repeated calculations.
3.2 Synchronous variables in multithreaded environments
In a multithreaded program,mutable
It can be used to modify locking or synchronize related variables, especially to avoid unnecessary locking when accessing data. For example, usemutable
To tag a data member, allowing it to be modified in a constant member function, so that the constant nature of the function itself is not necessary during lock operation.
Example: Thread-safe counter
#include <iostream> #include <mutex> using namespace std; class ThreadSafeCounter { private: mutable int count; // Counter mutable mutex mtx; // Mutex lock for synchronizationpublic: ThreadSafeCounter() : count(0) {} void increment() const { lock_guard<mutex> lock(mtx); count++; } int getCount() const { lock_guard<mutex> lock(mtx); return count; } }; int main() { ThreadSafeCounter counter; (); cout << "Counter: " << () << endl; // Output: Counter: 1 return 0; }
explain:
- Even in
increment
andgetCount
When a function is a constant function,count
andmtx
It can still be modified in these two functions. By usingmutable
and mutex, we ensure thread safety in multithreaded environments.
4. Limitations of mutable keywords
Althoughmutable
It's powerful, but it also has limitations:
-
mutable
It can only be applied to class member variables, and cannot be applied to local variables, global variables, etc. - It can only modify the state of the object and does not allow the object's constant interface to be directly modified.
Therefore, usemutable
Be careful when you are in the process of making sure it conforms to the design pattern and code structure.
5. Classic questions in interviews
In the C++ interview, aboutmutable
Common questions may include the following aspects:
-
mutable
andconst
What is the relationship?-
mutable
Allows to modify member variables even in constant member functions,const
Make sure that member functions cannot modify member variables. When the two are used in combination,const
limits the behavior of the function itself, andmutable
Make certain member variables not subject to this limitation.
-
-
mutable
What scenarios are mainly used for?-
mutable
It is mainly used in scenarios such as caching, delay calculation, thread safety, etc. where the internal state of the object needs to be modified in constant member functions.
-
- If a class member variable is
mutable
Modification, does this mean that the member variable affects the constantity of the object?- Won't. Member functions are marked as
const
when, it means that the function will not modify the state of the object, butmutable
Allows modifying certain member variables in constant member functions without changing the constantity of the object. 6.Summarize
- Won't. Member functions are marked as
mutable
Keywords are a very useful feature in C++ that allows us to modify specific member variables in constant member functions. Common usage scenarios include:
- Cache mechanism: Caches the calculation results in constant functions to avoid repeated calculations.
- Multithreaded synchronization: Allows modifying synchronous variables in constant functions for thread-safe operations.
mastermutable
The use of this can make your code more flexible and efficient, especially when designing caches, delayed computing or multi-threaded synchronization. Understand and applymutable
It will make you stand out in the interview and show your in-depth understanding of C++. 💡
This is the article about the role and usage scenario analysis of mutable keywords in C++. For more related content of mutable keywords, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!