Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is mutable const?

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);
}
like image 764
shainu vy Avatar asked Jul 20 '17 03:07

shainu vy


People also ask

What is mutable type in C++?

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.

What is mutable function?

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.

Is const mutable Javascript?

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.

What is mutable data member in C++?

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.


1 Answers

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.

like image 51
Matt Timmermans Avatar answered Sep 22 '22 17:09

Matt Timmermans