mutable变量的典型例子就是我们一类:
class Test
{
private:
int curpos;
int value[100];
public:
/*operations*/
};
其中curpos表示当前内部数组当前元素的位置信息
,我们就可以把这个变量声明为mutable,因为curpos改变了,
我们因为数组本身实际并没有改变的,所以我们可以认为对象状态也没有改变的。
no. const has two semantics:
1. const in implementation. which means you don't change any member variable.
2. const in observable behavior, which means you may change some internal state, but the execution of this method would not affect the observable behavior. Example would be like caching (as ccmouse said)
But that's not for good-looking. It's for a safer type system.
For the second case, you may need mutable variable.
mutable member variable就是在const member function中也能修改的变量。
比如,你的类要格式化一个输出,第一次算了许久,最后把它放入成员buffer,在这样的情况下,用const修饰print(),mutable修饰buffer,比较美观。
我也觉得只是美观而已。
This keyword can only be applied to non-static and non-const data
members of a class. If a data member is declared mutable, then it
is legal to assign a value to this data member from a const member
function.
const means you cannot change the state of the object.
state means all the values of the members in that object.
While in some special cases, you don't consider a member in an object as part of the state(it may be just for temporary storage, or the change of it does not change the observable behavior of your object) you may declare it as mutable.