Search code examples
c++staticdeclarationsemanticsmutable

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;
};

I think static mutable int n; has clear semantics in some cases. Why is it not allowed in C++?

Update:

Another example to show 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;
};

Solution

  • You said:

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

    That's a misunderstanding. A static member variable can be modified in a const member function since the former is not associated with a specific instance of the class. Hence, the notion of mutable for a static member variable does not make much sense.