I want to know how mutable affects a container (map, vector, list, ...). In addition, what do I have to bear in mind?
The keyword mutable is mainly used to allow a particular data member of const object to be modified. When we declare a function as const, the this pointer passed to function becomes const. Adding mutable to a variable allows a const pointer to change members.
- The mutable keyword allows the data member of a class to change within a const member function. - It allows to assign the values to a data member belonging to a class defined as “Const” or constant. - It allows a const pointer to change members.
The mutable storage class specifier is used only on a class data member to make it modifiable even though the member is part of an object declared as const . You cannot use the mutable specifier with names declared as static or const , or reference members.
A variable marked mutable allows for it to be modified in a method declared const . A variable marked volatile tells the compiler that it must read/write the variable every time your code tells it too (i.e. it cant optimize away accesses to the variable).
mutable
, like const
, is just a compile-time thing. It just allows you to modify that variable in a constant context. At runtime, there is no difference wether you declared the container mutable
or not.
class Foo{
mutable int i;
public:
void foo() const{
// constant context, but you can modify `i`
i = 5;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With