`mutable` — C++ Keyword

`mutable` — C++ Keyword

The mutable keyword in C++: allows a data member to be modified even in a const object.

How to use this reference page

Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.

  • Scan the top of the page first to identify the primary types, functions, or algorithm families involved.
  • Use the nearby-page links when your question is really about a companion header, related algorithm family, or broader subsystem.
  • Validate tricky behavior with a small compileable example before relying on memory for details like invalidation, ordering, allocation, or lifetime rules.

mutable

Allows 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.

Syntax

class Name {
    mutable Type member_;
};

Example

#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
}

Notes

Example in practice

int 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;
}