Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between logical and physical const-ness

Tags:

c++

What is the difference between these two terms, and why do I need mutable?

like image 684
rookie Avatar asked Sep 30 '10 12:09

rookie


People also ask

What is Bitwise Constness?

Bitwise const means that every bit in the object is permanent, so a bit image of the object will never change.

What is const correctness in C++?

By Alex Allain. The const keyword allows you to specify whether or not a variable is modifiable. You can use const to prevent modifications to variables and const pointers and const references prevent changing the data pointed to (or referenced).


2 Answers

"Physical" constness comes from declaring an object const, and could, in principle, be enforced by placing the object in read-only memory, so it cannot change. Attempting to change it will cause undefined behaviour; it might change, or it might not, or it might trigger a protection fault, or it might melt the memory chip.

"Logical" constness comes from declaring a reference or pointer const, and is enforced by the compiler. The object itself may or may not be "physically" const, but the reference cannot be used to modify it without a cast. If the object is not "physically" const, then C++ allows you to modify it, using const_cast to circumvent the protection.

A mutable class member can be modified even if the class object itself (or the reference or pointer used to access it) is const. Examples of good uses of this are a mutex that must be locked during a read operation, and a cache to store the result of an expensive read operation. In both cases, the operation itself should be a const function (since it doesn't affect the visible state of the object), but it needs to modify the mutex or the cache, so these need to be mutable. It can also be abused to make the object visibly change when logically it shouldn't, so use it with care; only declare members mutable if they don't form part of the externally visible state.

like image 87
Mike Seymour Avatar answered Sep 22 '22 09:09

Mike Seymour


You need mutable when there are fields in an object that can be considered "internal", i.e. any external user of the class cannot determine the value of these fields. The class might need to write to these fields even though the instance is considered constant, i.e. not changing.

Consider a hard drive; its cache is an example of such state. The cache is written to when data is read from the actual disk.

This is not possible to express cleanly in C++ without making the corresponding members mutable, to allow them to be changed even in methods marked const. As pointed out in a comment, you can always reach for the hammer and use a const_cast<> to remove the const-ness, but that is of course cheating. :)

like image 21
unwind Avatar answered Sep 23 '22 09:09

unwind