I regularly use const
when working with in-memory data structures and keep my code const-correct, but I'm not sure how const
should apply to more complex objects, such as the following:
- objects representing connections to remote systems
- objects backed by a database (that may load parts from the database on demand)
- objects backed by an on-disk directory tree (with access to the directory tree controlled by a separate object hierarchy)
What should const
methods signify for objects like these? I can think of a couple of possibilities:
- "strict" const - Methods which don't modify any in-memory state are const. However, this would seem to break encapsulation, since it would require callers to know which methods modify the connection state and which don't.
- "logical" const - Methods which don't modify the logical state of the object are const. However, this would potentially require marking a lot of state and caching variables as
mutable
. Although I realize that's whatmutable
is designed for, using it this much feels like a hack. Also, given that const means "I promise not to modify this," it doesn't seem right to apply it when methods may modify the state of the connection in strange and wonderful ways (as long as they maintain encapsulation), cache results as much as they want, throw exceptions if the connection fails, etc. - No const - In light of the preceding problems, does const simply not have much meaning for more complicated objects?
Which approach is most useful? Which is most common?