Mutable data member in C ++

1

Good morning everyone,

to see if you remove the doubt. A constant function in theory is only used with const data members that do not modify the object, that is, this function will access a const data member but as I am looking at it, when we add mutable to a data:

class x
{
private:
mutable int miembro_datos;
}

This member can be used with const functions and can also be modified, which leads to a controversy.

Can someone help me to understand the mutable attribute? Why with mutable can you change the data of an object through a const function? In theory you should not allow your modification, no?

Thanks

    
asked by ProgrammerJr 11.01.2018 в 23:37
source

1 answer

4
  

Why with mutable can you change the data of an object through a function const ?

Because that's how C ++ works; it is a characteristic of the language described in the language standard (my translation):

  

10.1.1 Storage specifiers in class

     
  • The mutable specifier should appear only in the declaration of non-static members whose type is not qualified as a constant or as a reference [ Example:

    class X {
        mutable const int* p; // BIEN
        mutable int* const q; // mal formado
      };
    
         

    - end of the example ]

  •   
  • The mutable specifier on a member of a class overrides the const specifier applied on the owner object and allows the modification of the mutable member object even though the rest of the object is const .
  •   

    So the modification of mutable sub-objects is not only allowed, but regulated in the standard.

    Other things to consider.

  • mutable does not propagate to pointers to member:

    struct S
    {
        mutable int i{};
    };
    
    int main()
    {
        const S s{100}; // s es constante.
        std::cout << s.i; // Muestra 100
    
        s.i = 200; // s.i es mutable, podemos cambiarlo aunque s sea constante
        std::cout << s.i; // Muestra 200
    
        auto pm = &S::i; // Apuntamos al miembro mutable
        (s.*pm) = 300; // Error de compilacion, s es constante
    
        return 0;
    }
    
  • Since the lambda generates a functor whose call operator is constant, its member data is constant, so mutable is required to modify the objects captured by value in lambdas:

    int i = 0;
    auto lambda = [i](){ i++; };
    auto mlambda = [i]() mutable { i++; };
    
    lambda();  // ERROR: i es constante
    mlambda(); // Correcto.
    
  • answered by 12.01.2018 / 08:51
    source