mutable 是C++ 中的关键字,用于在 const 成员函数中修改成员变量,允许特定成员变量即便在 const 对象或 const 成员函数中也能被改变。
1. 核心功能
- 突破const限制:能在
const 成员函数中对被 mutable 修饰的成员变量进行修改。
- 保持逻辑常性:允许修改不影响对象“逻辑状态”的内部实现细节。
2. 基本用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Example { private: mutable int cache; int value;
public: Example(int v) : value(v), cache(0) {}
int getValue() const { if (cache == 0) { cache = value * 2; } return cache; } };
|
3. 常见应用场景
3.1. 缓存机制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class DataProcessor { private: mutable int resultCache; mutable bool cacheValid; int rawData;
public: DataProcessor(int data) : rawData(data), resultCache(0), cacheValid(false) {}
int getProcessedResult() const { if (!cacheValid) { resultCache = rawData * 100 + 50; cacheValid = true; } return resultCache; }
void updateData(int newData) { rawData = newData; cacheValid = false; } };
|
3.2. 互斥锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include <mutex>
class ThreadSafeCounter { private: mutable std::mutex mtx; int count;
public: ThreadSafeCounter() : count(0) {}
int getCount() const { std::lock_guard<std::mutex> lock(mtx); return count; }
void increment() { std::lock_guard<std::mutex> lock(mtx); ++count; } };
|
3.3. 引用计数或调试信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Resource { private: mutable int accessCount; int data;
public: Resource(int d) : data(d), accessCount(0) {}
int getData() const { ++accessCount; return data; }
int getAccessCount() const { return accessCount; } };
|
4. 重要注意事项
- 不能用于静态成员
1 2 3 4
| class MyClass { mutable static int x; static int y; };
|
- 不能用于引用成员
1 2 3
| class MyClass { mutable int& ref; };
|
- 不能用于const成员
1 2 3
| class MyClass { mutable const int x; };
|
5. 设计原则
使用 mutable 需遵循逻辑常性原则:
- 对象“逻辑状态”保持不变。
- 修改的仅是“物理状态”或实现细节。
- 不影响对象公开行为。
1 2 3 4 5 6 7 8 9 10 11 12 13
| class GoodDesign { private: mutable std::string logBuffer; mutable int debugCounter; int importantData;
public: void process() const { debugCounter++; } };
|
6. 总结
mutable 提供了在保持 const 语义的同时允许特定成员修改的机制,一句话总结:
mutable = 允许 const 成员函数修改这个成员变量。
它不破坏对象的逻辑常性,只修改内部实现细节。
常用于:
- 实现缓存和延迟计算。
- 管理同步原语(如互斥锁)。
- 收集统计和调试信息。
- 实现内部状态管理而不破坏
const 正确性。
正确使用 mutable 可提升代码灵活性与性能,但需谨慎,确保不破坏 const 语义完整性。