Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is modifying a mutable member of a const object valid?

In C++ you can now have mutable members. This adds a layer of "logical const" to the language. How do these relate to read only data - will having a mutable member prevent a const class from being put into a .rodata section?

class Foo {
    mutable int bar;

public:
    Foo(): bar(0) {}
    void set(int x) const { bar = x; }
};

// Can this be in a read-only section?
const Foo foo;

int main(void)
{
    // Is this well-defined?
    foo.set(5);
}
like image 683
Kevin Cox Avatar asked Mar 18 '23 22:03

Kevin Cox


2 Answers

Yes, you are allowed to modify mutable members of const objects, this is covered in the draft C++ standard section 7.1.1 Storage class specifiers which says:

The mutable specifier on a class data member nullifies a const specifier applied to the containing class object and permits modification of the mutable class member even though the rest of the object is const (7.1.6.1).

The Technical Report on C++ Performance section 7.1 ROMability covers the cases when a compiler could put data in read-only memory. In this case that would not be possible since it is clearly not immutable:

The subject of ROMability therefore has performance application to all programs, where immutable portions of the program can be placed in a shared, read-only space.

like image 77
Shafik Yaghmour Avatar answered Mar 21 '23 12:03

Shafik Yaghmour


Yes mutable member can be modified in const method and most probably will remove that object ROMability. There are also other requirement to make an instance of class ROMable. Details can be found in Techincal Report on C++ Perfomance chapter 7 and here

like image 36
Slava Avatar answered Mar 21 '23 10:03

Slava