Mutable Class Members

Common Use Cases for mutable

What are some common use cases for the mutable keyword?

Abstract art representing computer programming

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:

Caching

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

Logging

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

Thread Safety

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.

This Question is from the Lesson:

Mutable Class Members

An introduction to the mutable keyword, which gives us more flexibility when working with const objects.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Mutable Class Members

An introduction to the mutable keyword, which gives us more flexibility when working with const objects.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved