SoFunction
Updated on 2025-04-09

Analysis of the role and usage scenarios of mutable keywords in C++ (latest recommendation)

In C++,mutableIt 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. understandmutableHow it works and its usage scenarios are very important for C++ developers.

1. Basic concepts of mutable keywords

mutableis 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, usemutableModified 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,setValueis a constant member function that attempts to modifyvalueMember variables can cause compilation errors.

usemutableSituation:

When we usemutableWhen 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:

  • valueIt's onemutableMember variables, so even insetValueIt can also be modified in such a constant member function.
  • Constant member functionssetValueThe member variable of the object should not be modified, but becausevaluequiltmutableModification, the compiler allows modification in this functionvalue

3. Common usage scenarios of mutable

3.1 Implementing the caching mechanism

mutableKeywords 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:

  • existgetResultIn a constant member function,cachedResultandisCacheValidquiltmutableModifications, so they can be modified even in constant functions. This allows us to update the cache without changing other states of the object.
  • performComplexCalculationIt 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,mutableIt can be used to modify locking or synchronize related variables, especially to avoid unnecessary locking when accessing data. For example, usemutableTo 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 inincrementandgetCountWhen a function is a constant function,countandmtxIt can still be modified in these two functions. By usingmutableand mutex, we ensure thread safety in multithreaded environments.

4. Limitations of mutable keywords

AlthoughmutableIt's powerful, but it also has limitations:

  • mutableIt 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, usemutableBe 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, aboutmutableCommon questions may include the following aspects:

  • mutableandconstWhat is the relationship?
    • mutableAllows to modify member variables even in constant member functions,constMake sure that member functions cannot modify member variables. When the two are used in combination,constlimits the behavior of the function itself, andmutableMake certain member variables not subject to this limitation.
  • mutableWhat scenarios are mainly used for?
    • mutableIt 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 ismutableModification, does this mean that the member variable affects the constantity of the object?
    • Won't. Member functions are marked asconstwhen, it means that the function will not modify the state of the object, butmutableAllows modifying certain member variables in constant member functions without changing the constantity of the object. 6.Summarize

mutableKeywords 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.

mastermutableThe use of this can make your code more flexible and efficient, especially when designing caches, delayed computing or multi-threaded synchronization. Understand and applymutableIt 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!