简体   繁体   中英

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);
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM