I didn't find any topics related to mutable const
on SO. I have reduced code to minimal working code (on visual studio). If we uncomment //*data = 11;
, the compiler complains about const-ness. I wonder how mutable const
works.
class A
{
public:
void func(int & a) const
{
pdata = &a;
//*pdata = 11;
}
mutable const int * pdata;
};
int main()
{
const A obj;
int a = 10;
obj.func(a);
}
Mutable data members are those members whose values can be changed in runtime even if the object is of constant type. It is just opposite to constant. Sometimes logic required to use only one or two data member as a variable and another one as a constant to handle the data.
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 const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
Mutable Data Members (C++)This keyword can only be applied to non-static and non-const data members of a class. If a data member is declared mutable , then it is legal to assign a value to this data member from a const member function.
This example is a little confusing, because the mutable
keyword is not part of the type specifier const int *
. It's parsed like a storage class like static
, so the declaration:
mutable const int *pdata;
says that pdata
is a mutable pointer to a const int.
Since the pointer is mutable, it can be modified in a const method. The value it points to is const, and cannot be modified through that pointer.
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