“mutable”关键字是否有任何目的,除了允许变量被const函数修改? [英] Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

查看:169
本文介绍了“mutable”关键字是否有任何目的,除了允许变量被const函数修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前一段时间,我遇到了一些用 mutable 关键字标记类的成员变量的代码。就我可以看到它只是允许你修改一个变量在 const 方法:

A while ago I came across some code that marked a member variable of a class with the mutable keyword. As far as I can see it simply allows you to modify a variable in a const method:

class Foo  
{  
private:  
    mutable bool done_;  
public:  
    void doSomething() const { ...; done_ = true; }  
};

这是唯一使用这个关键字还是有更多的,我已经在一个类中使用了这种技术,标记一个 boost :: mutex 为可变的允许 const

Is this the only use of this keyword or is there more to it than meets the eye? I have since used this technique in a class, marking a boost::mutex as mutable allowing const functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.

推荐答案

它允许差异化的位常数和逻辑常量。逻辑const是当对象不以通过公共接口可见的方式改变时,例如您的锁定示例。另一个例子是一个类,它在第一次请求它时计算一个值,并缓存结果。

It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result.

由于可以在lambda上使用c ++ 11 mutable 表示由值捕获的事物是可修改的它们不是默认值):

Since c++11 mutable can be used on a lambda to denote that things captured by value are modifiable (they aren't by default):

int x = 0;
auto f1 = [=]() mutable {x = 42;};  // OK
auto f2 = [=]()         {x = 42;};  // Error: a by-value capture cannot be modified in a non-mutable lambda

这篇关于“mutable”关键字是否有任何目的,除了允许变量被const函数修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆