xml*_*lmx 2 c++ static declaration mutable semantics
struct A
{
// clang 3.8 error : cannot combine with previous 'static' declaration specifier
static mutable int n;
};
Run Code Online (Sandbox Code Playgroud)
我认为static mutable int n;在某些情况下有明确的语义.为什么在C++中不允许这样做?
更新:
另一个例子显示clear semantics:
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;
};
Run Code Online (Sandbox Code Playgroud)
你说:
Run Code Online (Sandbox Code Playgroud)// _mtx must be mutable, because this is in const member function
这是一个误解.甲static成员变量可以在一个被修改const的成员函数,因为前者不与类的特定实例相关联.因此,这一概念mutable的static成员变量并没有太大的意义.