troubleshooting Question

Valid use of the keyword mutable?

Avatar of mrwad99
mrwad99Flag for United Kingdom of Great Britain and Northern Ireland asked on
16 Comments1 Solution523 ViewsLast Modified:
Ah hello.

I would like opinions on the use of the keyword mutable, and whether or not how I have used it, described below, is valid.  Please consider the pseudo code below:
class CStore
	CObject* GetObject(const std::string& strName)
		// Retrieve item "strName" using lower_bound() or equivalent
	void SortAlphabetically()
		// Sorts m_storage alphabetically

	std::vector<CObject*> m_storage;

OK.  I had code similar to the above, and was looking to tidy it up.  I had the brainwave that GetObject() should be const; after all, it does not modify the object in any way.  I then had to make SortAlphabetically() const for obvious reasons.

This lead to a problem.  GetObject() should be const; but should SortAlphabetically() really also be const?  I did some reading and found out about "logical constness" vs "bitwise constness", and realised that SortAlphabetically() could be made const as although it does change the bit-pattern of the CStore object, it would not change the way the object appears to clients (so hence remains logically const).

Feeling appeased, the final piece of the solution was to make m_storage mutable, which I did, then happily continued pounding my keyboard writing new code.

For a short while.

A little nag came into my mind; having made m_storage mutable, what was to stop somebody modifying my class and writing a new function like this:
void CStore::DoNothingSpecial() const

Eeek!  Because m_storage is mutable it can be adjusted in whatever way required, so client code could call this function assuming nothing about the CStore object will change, but in reality after the call to DoNothingSpecial() it is completely different to before the call.

Am I right to be concerned with the above, or is it assumed that the anyone modifying the class will not do (stupid) things like this?

How would you get around this issue?

Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 16 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 16 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros