std::mutable

In C++, the mutable keyword is used as a qualifier for class member variables. When applied to a member variable, it signals that the variable may be modified even if the member function in which it is being modified is declared as a const member function. This allows modifying certain class members within const member functions without violating the const-correctness of the function.

The mutable keyword is particularly useful when you have a member variable that logically does not affect the state of the object, but you still want to modify it within const member functions or methods.

#include <iostream>

class Example {
public:
    void setX(int value) const {
        // x_ can be modified within a const member function
        x_ = value;
    }

    void printX() const {
        std::cout << x_ << std::endl;
    }

private:
    mutable int x_;
};

int main() {
    Example obj;
    obj.setX(42);
    obj.printX();

    return 0;
}

In this example, x_ is declared as mutable, which means it can be modified even inside member functions that are marked as const. The setX member function modifies x_, and it is declared as const. Without the mutable keyword, attempting to modify x_ inside a const member function would result in a compilation error.

When using the mutable keyword, it’s essential to use it judiciously. Overusing mutable might be a sign that the class design could be improved. It’s typically recommended to keep the number of mutable variables minimal and well-documented to avoid confusion.