mutable Keyword

The mutable keyword is used in declarations of class members. It allows certain members of constant objects to be modified in spite of the const of the containing object.

Usage

Often some class members are part of the implementation of the object, not part of the actual information stored by the object. Although the information in the object needs to stay unmodified in a const object, the implementation members may need to change. These are declared mutable.

An example of this is use or reference count in an object that keeps track of the number of pointers referring to it.

Example

class C { public:

C(); int i; mutable int j;

};

C::C() : i(1), j(3)

{

// Define constructor

}

int main()

{

const C c1; C c2;

// c1.i =0;

// Problem: compilation error

 

// Message: The left side of ‘=’

 

// must be a modifiable lvalue.

c1.j = 1;

// OK

c2.i = 2;

// OK

c2.j = 3;

// OK

}

 

The mutable keyword can only be used on class data members. It cannot be used for const or static data members. Notice the difference in the two pointer declarations below:

class C {

 

C() { }

// define constructor

mutable const int *p;

// OK

 

// mutable pointer to int const

 

// p in constant C object

 

// can be modified

mutable int *const q;

// Compile time error

 

// mutable const pointer to int

 

// const data member can’t be

 

// mutable

 

// Message: ‘mutable’ may be

 

// used only in non-static

 

// and non-constant data

 

// member declarations within

 

// class declarations

};

 

HP aC++ Keywords 143

Page 143
Image 143
HP C/aC++ for PA-RISC Software manual Mutable Keyword