C++ Reference ยท Keywords and Statements
The mutable specifier
Reference for C++ mutable: data members that can change inside const member functions, caches and mutexes, and mutable lambdas that modify their copies.
mutable has two uses, both about relaxing const. On a data member, it exempts that member from the constness of the object: a const member function (or a const object) may still modify it. On a lambda, [x]() mutable { ... } lets the lambda body modify its by-copy captures.
The guiding principle is logical constness. A function should be const if the observable state of the object does not change, even if hidden bookkeeping (a cache, a counter, a lock) does.
class Report { mutable std::string cache_; // may change inside const methods public: const std::string& text() const; };
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Syntax
mutable type member; // inside a class definition [captures](params) mutable { body } // mutable lambda
| Use | Effect |
|---|---|
mutable data member |
The member is never treated as const, even in a const object or inside a const member function. |
mutable lambda |
The lambda's call operator is not const, so by-copy captures can be modified. Each lambda object keeps its own state between calls. |
Usage notes
mutablecannot be applied to references, toconstmembers, or to static members.- Typical members: caches, lazily computed values, access counters, debug statistics and synchronization primitives (
std::mutex,std::atomicflags). - Modifying a
mutablemember of a genuinelyconstobject is not undefined behavior. Modifying a non-mutable member throughconst_castis. - A
constmethod that changes amutablecache must still be safe to call from several threads if the class promises thread-safe const access: protect the cache with a mutex or atomics. The standard library requires const member functions to be thread-safe. - Without
mutable, a lambda'soperator()isconst, and[n]() { ++n; }is an error. Capture by reference ([&n]) to change the outer variable instead. - A mutable lambda is not equivalent to a function with
staticstate: each copy has its own captured value, as the second example shows. - Since C++23 the empty parameter list may be omitted even when
mutableis present:[n] mutable { return ++n; }. Before C++23 you must write[n]() mutable { ... }. - Use
mutablesparingly. If a method changes visible behavior, do not make itconst.