为什么在 C++ 中不允许 "static mutable int n;"?

Why is "static mutable int n;" not allowed in C++?

struct A
{
    // clang 3.8 error : cannot combine with previous 'static' declaration specifier
    static mutable int n;
};

我认为 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;
};

A static class 成员变量未绑定到 class.
的实例 因此 mutable 通过从 const class 实例 访问和更改值来改变行为将没有任何意义。


关于您随更新提供的示例:

 // _mtx should be mutable, 
 // because this is in const member function

std::mutex _mtx; 不应该是 static 成员。您不需要锁定 SharedValue 的所有实例 ,而只需锁定当前的实例(即使没有,您也不需要提供 mutable _mtx 对于 static 成员是可变的,它已经是)。

只需省略 static 关键字,使用 mutable 互斥锁是一种常用技术。

你说:

   // _mtx must be mutable, because this is in const member function

这是误会。 static 成员变量可以在 const 成员函数中修改,因为前者与 class 的特定实例无关。因此,mutable 对于 static 成员变量的概念没有多大意义。

没有明确的可能语义,因为标准不支持该关键字组合。

在原始的C语言中,关键字通常具有助记值。

在当前的 C++ 中,关键字已被重复使用,因此它们具有多种含义,例如static(这是您的关键字之一)的多重含义。


注意非static成员函数的const-ness是关于*thisconst-ness,与[=无关11=]-static 数据成员的特性。

如果我们要为 mutable 定义一些并非完全不自然的含义应用于 static 数据成员,它必须与 const for static 成员函数。这是另一种可能的语言扩展。

您可以通过定义一个单独的 class 来保持 static 状态来实现对可变性的限制。