mutable

suggest change

A specifier that can be applied to the declaration of a non-static, non-reference data member of a class. A mutable member of a class is not const even when the object is const.

class C {
    int x;
    mutable int times_accessed;
  public:
    C(): x(0), times_accessed(0) {
    }
    int get_x() const {
        ++times_accessed; // ok: const member function can modify mutable data member
        return x;
    }
    void set_x(int x) {
        ++times_accessed;
        this->x = x;
    }
};

A second meaning for mutable was added in C++11. When it follows the parameter list of a lambda, it suppresses the implicit const on the lambda’s function call operator. Therefore, a mutable lambda can modify the values of entities captured by copy. See mutable lambdas for more details.

std::vector<int> my_iota(int start, int count) {
    std::vector<int> result(count);
    std::generate(result.begin(), result.end(),
                  [start]() mutable { return start++; });
    return result;
}

Note that mutable is not a storage class specifier when used this way to form a mutable lambda.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


keywords:
* class
* float
* bool
* void
* char
* short
* long
* double
* int
* enum
* if
* do
* else
* true
* false
* const
* for
* goto
* struct
* case
* mutable
* catch
* return
* signed
* static
* this
* switch
* throw
* try
* break
* union
* asm
* sizeof

Table Of Contents
8 Arrays
11 Loops
14 keywords
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype