In Section 21.2, we introduced the const_cast
operator, which allowed us to remove the “const
-ness” of a type. A const_cast
operation can also be applied to a data member of a const
object from the body of a const
member function of that object’s class. This enables the const
member function to modify the data member, even though the object is considered to be const
in the body of that function. Such an operation might be performed when most of an object’s data members should be considered const
, but a particular data member still needs to be modified.
As an example, consider a linked list that maintains its contents in sorted order. Searching through the linked list does not require modifications to the data of the linked list, so the search function could be a const
member function of the linked-list class. However, it’s conceivable that a linked-list object, in an effort to make future searches more efficient, might keep track of the location of the last successful match. If the next search operation attempts to locate an item that appears later in the list, the search could begin from the location of the last successful match, rather than from the beginning of the list. To do this, the const
member function that performs the search must be able to modify the data member that keeps track of the last successful search.
If a data member such as the one described above should always be modifiable, C++ provides the storage-class specifier mutable as an alternative to const_cast
. A mutable
data member is always modifiable, even in a const
member function or const
object.
Portability Tip 21.1
The effect of attempting to modify an object that was defined as constant, regardless of whether that modification was made possible by a const_cast or C-style cast, varies among compilers.
mutable
and const_cast
are used in different contexts. For a const
object with no mutable
data members, operator const_cast
must be used every time a member is to be modified. This greatly reduces the chance of a member being accidentally modified because the member is not permanently modifiable. Operations involving const_cast
are typically hidden in a member function’s implementation. The user of a class might not be aware that a member is being modified.
Software Engineering Observation 21.1
mutable members are useful in classes that have “secret” implementation details that do not contribute to a client’s use of an object of the class.