struct A
{
// clang 3.8 error : cannot combine with previous 'static' declaration specifier
static mutable int n;
};
我认为 static mutable int n;
在某些情况下语义清晰。 为什么在 C++ 中不允许?
更新:
显示清晰语义
的另一个例子:
class SharedValue
{
public:
void Set(int n)
{
std::lock_guard lock(_mtx);
_n = n;
}
int Get() const
{
std::lock_guard lock(_mtx);
//
// _mtx should be mutable,
// because this is in const member function
//
return _n;
}
private:
static mutable std::mutex _mtx;
int _n;
};
最佳答案
你说:
// _mtx must be mutable, because this is in const member function
这是误会。 static
成员变量可以在 const
成员函数中修改,因为前者与类的特定实例无关。因此,对于 static
成员变量来说,mutable
的概念没有多大意义。
关于c++ - 为什么在 C++ 中不允许使用 "static mutable int n;"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41052915/