concept mutable in category c++

This is an excerpt from Manning's book Functional Programming in C++.
One thing worth noting is that the call operator of lambdas is constant by default (contrary to the other parts of the language, where you need to explicitly specify that something is
const). If you want to change the value of the captured variables, when they’re captured by value and not by reference, you’ll need to declare the lambda asmutable. In the following example, you use thestd::for_eachalgorithm to write all words beginning with an uppercase letter, and you use thecountvariable to count the number of words you wrote. This is sometimes useful for debugging, but mutable lambdas should be avoided. Obviously, there are better ways to do this, but the point here is to demonstrate how mutable lambdas work.
This can be solved by creating a
mutablemember variable in your class—a member variable that can be changed even fromconstmember functions. Because you want to guarantee that your class is immutable from the user’s perspective, you have to ensure that two concurrent calls toemployment_historycan’t return different values. You need to ensure that the second call isn’t executed until the first one finishes loading the data.Listing 5.8 Using
mutableto implement cachingclass person_t { public: employment_history_t employment_history() const { std::unique_lock<std::mutex> #1 lock{m_employment_history_mutex}; #1 if (!m_employment_history.loaded()) { #2 load_employment_history(); #2 } #2 return m_employment_history; #3 } #4 private: mutable std::mutex m_employment_history_mutex; #5 mutable employment_history_t m_employment_history; #5 … }; #1 Locks the mutex to guarantee that a concurrent invocation of employment_history can’t be executed until you finish retrieving the data from the database #2 Gets the data if it isn’t already loaded #3 The data is loaded; you’re returning it to the caller. #4 When you exit this block, the lock variable will be destroyed and the mutex will be unlocked. #5 You want to be able to lock the mutex from a constant member function, so it needs to be mutable as well as the variable you’re initializing.