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

标签 c++ static declaration semantics mutable

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/

相关文章:

c - 等效的 C 声明

c++ 'static int' 不能跨多个文件工作吗?

c++ - 从数组更改值

c++ - 继承一个带有内部类的模板类,并在继承类中访问内部类

Java静态引用与动态引用和调用

c - 'for' 循环初始声明中的静态变量

c++ - 如何使 Sprite 在 c++/sfml 2.1 中消失?

c++ - 在旧的 Borland C 中使用 Visual C++ DLL?

java - 有多少()可以在Java中调用非静态方法?

复杂声明