beginner C++ question (int increment)

If Ive got this right (sorry im a pascal programmer) mutable allows a constant to be changed
Thats bloody stupid...
 
Mutable is there for the specific reason I gave.
In the case of a const member function, the semantic is that it does not modify class state.
I.e. it's a getter of some sort.
However it is common in the implementation of a getter to cache computed results, since the cache is part of the class state, without mutable that would mean that you could not declare the member const and no function above it could take a const value.
In practice that means that trying to be const correct in the rest of the application is now impossible.

It's the difference between the interface semantics and the implementation.

As I said in practice people fall in to two camps, ignore const entirely, or try and do the right thing until it becomes impractical.
 
mutable and const cant be specified for the same variable. mutable denotes its not changing the (formal) state of an object (a const function call with the same parameters is guaranteed to have the same result aslong as you dont change the state), think of cached views.

for the compiler this allows certain optimizations, consider:
Code:
for (SomeIterator it = container.begin(); it != container.end(); ++it) {/*blahblah*/}

here container.end() is called each iteration, should the end() method be const the compiler can call it just once and then use the result each time.
 
Back
Top