不久前,我遇到了一些代码,它们用mutable关键字标记了一个类的成员变量。据我所知,它只是允许你在const方法中修改变量:

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

这是唯一的使用这个关键字还是有更多的它比满足眼睛?从那以后,我在一个类中使用了这种技术,将boost::mutex标记为mutable,允许const函数出于线程安全的原因锁定它,但是,说实话,这感觉有点hack。


当前回答

Mutable is used when you have a variable inside the class that is only used within that class to signal things like for example a mutex or a lock. This variable does not change the behaviour of the class, but is necessary in order to implement thread safety of the class itself. Thus if without "mutable", you would not be able to have "const" functions because this variable will need to be changed in all functions that are available to the outside world. Therefore, mutable was introduced in order to make a member variable writable even by a const function.

指定的可变变量通知编译器和读取器 成员变量可以在const中修改,这是安全和预期的吗 成员函数。

其他回答

Mutable将const的含义从按位的const更改为类的逻辑const。

这意味着具有可变成员的类将不再是按位的const,并且将不再出现在可执行文件的只读部分中。

此外,它通过允许const成员函数在不使用const_cast的情况下更改可变成员来修改类型检查。

class Logical {
    mutable int var;

public:
    Logical(): var(0) {}
    void set(int x) const { var = x; }
};

class Bitwise {
    int var;

public:
    Bitwise(): var(0) {}
    void set(int x) const {
        const_cast<Bitwise*>(this)->var = x;
    }
};

const Logical logical; // Not put in read-only.
const Bitwise bitwise; // Likely put in read-only.

int main(void)
{
    logical.set(5); // Well defined.
    bitwise.set(5); // Undefined.
}

请参阅其他答案了解更多细节,但我想强调的是,这不仅仅是为了类型安全,而且它会影响编译结果。

经典的例子(在其他回答中提到),也是我迄今为止看到的使用mutable关键字的唯一情况,是用于缓存复杂的Get方法的结果,其中缓存是作为类的数据成员实现的,而不是作为方法中的静态变量(出于几个函数之间共享或简单清洁的原因)。

一般来说,使用mutable关键字的替代方法通常是方法中的静态变量或const_cast技巧。

另一个详细的解释在这里。

当你重写一个const虚函数并想要修改该函数中的子类成员变量时,mutable可以很方便。在大多数情况下,您不希望更改基类的接口,因此必须使用自己的可变成员变量。

对于那些对用户来说是逻辑上无状态的东西(因此在公共类的api中应该有“const”getter),但在底层实现(你的.cpp中的代码)中不是无状态的东西,使用“mutable”。

The cases I use it most frequently are lazy initialization of state-less "plain old data" members. Namely, it is ideal in the narrow cases when such members are expensive to either build (processor) or carry around (memory) and many users of the object will never ask for them. In that situation you want lazy construction on the back end for performance, since 90% of the objects built will never need to build them at all, yet you still need to present the correct stateless API for public consumption.

在某些情况下(比如设计糟糕的迭代器),类需要保留一个计数或其他一些附带的值,这并不真正影响类的主要“状态”。这是我最常看到使用mutable的地方。如果没有mutable,您将被迫牺牲设计的整个const-ness。

对我来说,大多数时候这也像个黑客。在非常非常少的情况下有用。