Home >Backend Development >C++ >Beyond Const Member Functions: What Other Uses Does the `mutable` Keyword Have in C ?
Does 'mutable' Have Wider Applications Beyond Mutable Members in Const Member Functions?
The 'mutable' keyword in C enables altering data members in const member functions. However, some may wonder if it has any other purpose.
In reality, the 'mutable' keyword differentiates between bitwise and logical 'const'. Logical 'const' indicates an object doesn't visibly change through its public interface. This includes scenarios like locking a mutex in a const function for thread safety, as the modification occurs within the object's internal state, not accessible externally.
Another application is caching computed values and accessing them via a mutable member function. Such a function can fetch the value once and store it, maintaining logical 'const' while still allowing for internal modifications.
Furthermore, C 11 introduced mutable lambdas. These allow captured variables, typically referenced by value, to be modified. For instance:
int x = 0; auto f1 = [=]() mutable {x = 42;}; // OK auto f2 = [=]() {x = 42;}; // Error
Here, 'f2' fails because non-mutable lambda captures are unmodifiable. Therefore, 'mutable' not only enables altering members in const member functions but also extends to differentiating between bitwise and logical 'const' and facilitating data modification in mutable lambdas.
The above is the detailed content of Beyond Const Member Functions: What Other Uses Does the `mutable` Keyword Have in C ?. For more information, please follow other related articles on the PHP Chinese website!