什么时候你使用C ++'mutable'关键字?

什么时候你使用C ++'mutable'关键字?

问题描述:

何时使用C ++ mutable 关键字?为什么?我不认为我曾经使用过这个关键字。我理解它用于诸如缓存(或者记忆)之类的东西,但是用于你需要在什么类和条件中使用它。

When have you used C++ mutable keyword? and why? I don't think I have ever had to use that keyword. I understand it is used for things such as caching (or perhaps memorization) but in what class and condition have you ever needed to use it in?

偶尔我使用它来标记一个mutex或其他线程同步原语为可变的,所以通常标记为 const 的访问器/查询方法仍然可以锁定互斥体。

Occasionally I use it to mark a mutex or other thread synchronisation primitive as being mutable so that accessors/query methods, which are typically marked const can still lock the mutex.

当需要为调试或测试目的来测试代码时,它有时也很有用,因为测试通常需要修改查询方法中的辅助数据。

It's also sometimes useful when you need to instrument your code for debugging or testing purposes, because instrumentation often needs to modify auxiliary data from inside query methods.