mutable
在 C++ 中,mutable
关键字是用来说明即使一个对象是常量,对象内的某个成员变量也可以被修改。通常,这个关键字用于类的成员变量。让我给你一个简单的例子来说明这个概念。
考虑一个类 Counter
,它有一个成员变量 value
来计数,还有一个 mutable
成员变量 cache
,用于缓存一些值。即使在一个 const
方法中,你仍然可以修改 cache
。
#include <iostream>
class Counter {
public:
Counter() : value(0), cache(0) {}
void increment() {
++value;
updateCache();
}
int getValue() const {
// Even though this method is const, it can still change the cache.
updateCache();
return value;
}
private:
int value;
// Declare cache as mutable
mutable int cache;
void updateCache() const {
// We can modify the cache because it is mutable
cache = value * value;
}
};
int main() {
const Counter cnt;
std::cout << "Initial value: " << cnt.getValue() << std::endl;
// Error: increment() is a non-const function, cannot be called on a const object.
// cnt.increment();
// Note: The above line will cause a compile error because increment() is not a const
// method, and we're trying to call it on a const instance of Counter.
return 0;
}
在这个例子中,即使 getValue()
是一个 const
方法,它仍然可以调用 updateCache()
去更新 cache
变量,因为 cache
被声明为 mutable
。
请注意,在 main()
函数中,我们创建了一个 const Counter
对象。通常,你不能在一个 const
对象上调用任何非 const
方法,也不能修改它的任何成员变量。但是由于 cache
是 mutable
的,getValue()
方法可以修改它。
在上面的代码中,如果你尝试取消注释 main()
函数中的 cnt.increment();
,你会得到一个编译错误,因为 increment()
不是一个 const
方法,因此它不能在 const
对象 cnt
上被调用。但是 getValue()
可以被调用,并且它可以修改 mutable
成员 cache
。