Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

mutable — modifiable members and lambdas

The mutable keyword allows a selected data member to change even in a const object. In a lambda it has a different role: it removes the call operator's default const qualification, allowing modification of modifiable copies of captured values.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

mutable T member;
[captures](parameters) mutable { body }

mutable has two uses. On a non-static class data member, it permits modification of that member even through a const object and inside a const member function. It does not relax restrictions on other members. The member itself cannot have reference type or a top-level const-qualified type: mutable const int* p; is valid, but mutable int* const p; is not.

In a lambda without an explicit object parameter, [seed]() mutable { return ++seed; } makes operator() non-const. This allows changes to the captured copy of seed; its state persists between calls on the same lambda object, while the original remains unchanged. Such a lambda cannot be called through a const object. mutable does not remove const from a captured value's type. Reference capture does not require mutable to modify a modifiable original. Combining mutable with static or an explicit object parameter is prohibited.

In the example, counter is a const object, but next() increments calls. Independently, the lambda increments its own copy of seed. The output is 1 2, followed by 11 12 10. mutable provides no synchronization between threads; use it deliberately, for example for internal bookkeeping, rather than to conceal changes to an object's logical value.

This entry targets C++23. The supplied document is an evolving working draft, not a frozen C++23 text. The compiler flag in the verification procedure selects C++23; it does not attest a production environment or a completed test.

Examples

#include <iostream>

struct Counter {
    mutable int calls = 0;

    int next() const {
        return ++calls;
    }
};

int main() {
    const Counter counter;
    std::cout << counter.next() << ' ' << counter.next() << '\n';

    int seed = 10;
    auto next = [seed]() mutable { return ++seed; };
    std::cout << next() << ' ' << next() << ' ' << seed << '\n';
}

Result

1 2
11 12 10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources