Back: The explicit Keyword
Forward: The typename Keyword
 
FastBack: The typename Keyword
Up: Changeable C++
FastForward: Compiler Quirks
Top: Autoconf, Automake, and Libtool
Contents: Table of Contents
Index: Index
About: About this document

16.2.7 The mutable Keyword


C++ classes can be designed so that they behave correctly when const objects of those types are declared. Methods which do not alter internal object state can be qualified as const:

 
class String
{
public:
  String (const char* s);
  ~String ();

  size_t Length () const { return strlen (buffer); }

private:
  char* buffer;
};

This simple, though incomplete, class provides a Length method which guarantees, by virtue of its const qualifier, to never modify the object state. Thus, const objects of this class can be instantiated and the compiler will permit callers to use such objects' Length method.

The mutable keyword enables classes to be implemented where the concept of constant objects is sensible, but details of the implementation make it difficult to declare essential methods as const. A common application of the mutable keyword is to implement classes that perform caching of internal object data. A method may not modify the logical state of the object, but it may need to update a cache--an implementation detail. The data members used to implement the cache storage need to be declared as mutable in order for const methods to alter them.

Let's alter our rather farfetched String class so that it implements a primitive cache that avoids needing to call the strlen library function on each invocation of Length ():

 
class String
{
public:
  String (const char* s) :length(-1) { /* copy string, etc. */ }
  ~String ();

  size_t Length () const
  {
    if (length < 0)
      length = strlen(buffer);
    return length;
  }

private:
  char* buffer;
  mutable size_t length;
}

When the mutable keyword is not available, your alternatives are to avoid implementing classes that need to alter internal data, like our caching string class, or to use the const_cast casting operator (see section 16.2.3 Casts) to cast away the `constness' of the object.



This document was generated by Gary V. Vaughan on February, 8 2006 using texi2html