← 返回文章列表

C++ 笔记:mutable 关键字

mutable 的作用

mutable 用于突破 const 成员函数的只读限制,允许在 const 成员函数中修改被标记的成员变量(常用于缓存结果、访问计数或内部互斥锁 std::mutex)。

使用限制

  • 只能修饰类中的非静态(non-static)数据成员。
  • 不能与 const 或 static 同时修饰同一成员。

简例

class Cache {
public:
    int getValue() const {
        ++accessCount_; // const 成员函数中可修改 mutable 成员
        return value_;
    }

private:
    int value_ = 42;
    mutable int accessCount_ = 0;
};