When have you used C++ mutable
keyword? and why? I don't think I have ever had to use that keyword. I understand it is used for things such as caching (or perhaps memorization) but in what class and condition have you ever needed to use it in?

- 119,891
- 44
- 235
- 294
-
5possible duplicate of [volatile vs. mutable in C++](http://stackoverflow.com/questions/2444695/volatile-vs-mutable-in-c) – Andrey Dec 29 '10 at 12:25
-
5Do you mean [memoization](http://en.wikipedia.org/wiki/Memoization)? Strange as it may seem, it's not a typo of "memorization" – R. Martinho Fernandes Dec 29 '10 at 12:25
-
@Andrey: wtf, how is that question even remotely similar – Dec 29 '10 at 12:29
-
1@acidzombie24 i think that answers given to it are pretty relevant here. that's why is is *possible* duplicate. if it is not it won't be closed. – Andrey Dec 29 '10 at 12:47
-
2@acidzombie24 please keep it clean and non-abusive – David Heffernan Dec 29 '10 at 16:53
-
1@David Heffernan: Keep what clean? I dont abuse keywords in programming thus this question :) – Dec 30 '10 at 01:35
-
I've seen it used with copy-on-write strings. – JimR Aug 09 '13 at 05:34
11 Answers
Occasionally I use it to mark a mutex or other thread synchronisation primitive as being mutable so that accessors/query methods, which are typically marked const
can still lock the mutex.
It's also sometimes useful when you need to instrument your code for debugging or testing purposes, because instrumentation often needs to modify auxiliary data from inside query methods.

- 6,428
- 1
- 30
- 39
-
13This, I have found to be the most common use for mutable in the code I have been working with. In fact I default to `mutable mutex` when declaring them, without ever thinking on whether the `mutable` keyword will be required by the language. After all, the `mutex` is not part of the state of the object. – David Rodríguez - dribeas Dec 29 '10 at 13:17
-
-
1This is sometimes called the "M&M Rule", mutable and mutexes (and atomics) go together (https://herbsutter.com/2013/05/24/gotw-6a-const-correctness-part-1-3/) – michaelmoo Mar 30 '22 at 19:59
I've used mutable in case of object caching results calculated from internal members:
class Transformation
{
private:
vec3 translation;
vec3 scale;
vec4 rotation;
mutable mat4 transformation;
mutable bool changed;
public:
Node()
{
[...]
changed = false;
}
void set_translation(vec3 _translation)
{
translation = _translation;
changed = true;
}
void set_scale(...) ...
mat4 get_transformation() const
{
if(changed)
{
// transformation and changed need to be mutable here
transformation = f(translation, scale, rotation); // This take a long time...
changed = false;
}
return transformation;
}
};
void apply_tranformation(const Transformation* transfo)
{
apply(transfo->get_transformation());
}

- 729
- 3
- 8
Google code search reveals a number of uses. For example, in an implementation of XTR cryptography, mutable members are used so that methods can return a reference to a result (preventing copies from being made).
For another example, Webkit uses it to lazily initialize member data (m_lineHeight).

- 124,830
- 17
- 198
- 235
In mock objects to capture the value of arguments of const functions in a member variable.
class Source
{
public:
virtual ~Source() {}
virtual std::string read(int count) const=0;
};
class SourceMock : public Source
{
public:
mutable std::vector<int> arguments;
std::string read(int count) const {
arguments.push_back(count);
return "...";
}
};
//TEST....
SourceMock mock;
//...
VERIFY(mock.arguments.size()==2);
VERIFY(mock.arguments[0]==3);
//...

- 8,351
- 1
- 29
- 33
-
+1 cool situation. I still have a hard time imagining when that would be use but i can believe this. – Dec 29 '10 at 12:30
I use it when locking a mutex for thread-safety. The mutex is marked as mutable so the methods that lock it can remain const.

- 76,700
- 56
- 158
- 197
I use mutable
for class members that are initialized on demand, especially from a database or source external to the program. This allows the "getter" functions to create the object on demand otherwise it is a constant method.

- 56,849
- 17
- 98
- 154
http://msdn.microsoft.com/en-us/library/4h2h0ktk%28v=vs.80%29.aspx would be the best example. Hey, I have learned something today!

- 2,837
- 3
- 38
- 51
-
I can see how that is useful but i still cant think of when i would actually do that (there always seems to be a better place to put that) – Dec 29 '10 at 12:30
-
Actually, I have stumbled a number of times upon this situation: firstly designed the class so that parts of its getters would be const and then add some more code which would use a the Ptr obtained from "const Ptr* Class::getSomeMember() const;" in such way the compiler complained about it "cannot use const Ptr* in this context" or something. Now I know how to fix that :) – kellogs Dec 29 '10 at 12:35
-
1
My template class implements reference-counter pattern. When it is passed to functions as argument with const modifier it is possible that reference can be increased anyway. So instead of const_cast mutable can be used.

- 23,277
- 13
- 73
- 121
-
hmm, interesting. Is it better to do YourTemplate
rather then const YourTemplate – Dec 29 '10 at 12:32? wouldnt that solve it? +1 anyways -
@acidzombie24 - if inner class is really const that is true, but for general purpose
is very restrictive. – Dewfy Dec 29 '10 at 12:36
mutable keyword allows you to modify a variable inside a const context
e.g:
class Person {
private:
mutable int age;
public:
Person(int age) : age(age) {
}
void setAge(int age) const {
Person::age = age;
}
int getAge() const {
return Person::age;
}
};
int main() {
Person person(23);
std::cout << "Person age " << person.getAge() << std::endl;
person.setAge(24);
std::cout << "Person modified age " << person.getAge() << std::endl;
return 0;
}

- 1,677
- 17
- 16
It can be used in many scenarios e.g
Loggers
, timing
, access counters
etc.
These can be called in const-qualified accessors without changing the state of the data.

- 755
- 3
- 11
- 28
It can also be used if inside a getter method (that is usually const), you need to update the stored returned value. As an example, suppose that you have an specific linked-list implementation. For performance issues, you keep the last calculated length of the list, but while returning the length, if the list has been modified, you compute it again, otherwise, you return the last cached value.
class MyLinkedList
{
public:
long getLength() const
{
if (lengthIsModified())
{
mLength = ...; // do the computation here
}
return mLength;
}
private:
mutable long mLength;
};
Warning: It is not that easy to always keep mLength up-to-date because of some specific operations (like merging) in the list.

- 8,257
- 4
- 33
- 62