C++中的mutable

在C++中,关键字mutable用于允许一个const对象的成员变量被修改。在使用mutable关键字修饰的成员变量的时候,可以在const成员函数中修改该变量。这是因为,const成员函数默认情况下不允许修改类的数据成员。

mutable关键字通常用于缓存变量(cache variable)。一个const成员函数可以使用mutable修饰的变量作为缓存,来避免重复计算。同时,由于该变量是mutable的,因此即使在const成员函数中,也可以被修改。

下面是一个示例:

class MyClass {
  public:
    void myFunc() const {
      if(!cacheValid) {
        // perform some heavy calculations
        // and store the result in cache
        cache = 42;
        cacheValid = true;
      }
      // use cache
    }
  private:
    mutable int cache;
    mutable bool cacheValid = false;
};

在上面的示例中,cache和cacheValid被标记为mutable,因此可以在const成员函数myFunc()中被修改。如果没有mutable关键字,cache和cacheValid就不能在const成员函数中被修改。

需要注意的是,mutable变量的修改只在当前对象中生效,不会影响到其他对象。因此,mutable变量不会破坏C++的const语义。

Xuanwei Zhang
Xuanwei Zhang
Software Engineer

My research interests include distributed database, distributed storage system and internet of things