`mutable` — C++ Keyword
`mutable` — C++ Keyword
The mutable keyword in C++: allows a data member to be modified even in a const object.
`mutable` — C++ Keyword
The mutable keyword in C++: allows a data member to be modified even in a const object.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
mutableAllows a data member to be modified in a const member function or through a const reference/pointer to the enclosing object. Typically used for caches, lazy initialization, and mutexes.
class Name {
mutable Type member_;
};
#include <print>
#include <string>
#include <mutex>
class Document {
public:
explicit Document(std::string text) : text_(std::move(text)) {}
// const member function, but can update the cache
std::size_t word_count() const {
if (!cache_valid_) {
cached_count_ = compute_words(text_);
cache_valid_ = true;
}
return cached_count_;
}
private:
std::string text_;
mutable std::size_t cached_count_ = 0;
mutable bool cache_valid_ = false;
mutable std::mutex mtx_; // mutable so const functions can lock
static std::size_t compute_words(const std::string& s);
};
int main() {
Document doc{"Hello world foo bar"};
std::println("{}", doc.word_count()); // 4
}
mutable on a lambda capture (C++14) allows the lambda body to modify a by-value capture: [x]() mutable { ++x; }.mutable can break the logical const-ness of a class; use it only when the modified member is genuinely an implementation detail.mutableint main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}