首页 文章

可变变量由非const成员函数更改

提问于
浏览
1

我正在学习C,我读到了: If a data member is declared mutable, then it is legal to assign a value to this data member from a const member function. 但是下面的代码编译没有任何错误或gcc的警告 . (这不是一个真实的代码示例,我只是编写它来测试mutable关键字)

class M
{
public:
  M(){x=10;};
  int getX() {x++; return x;};
private:
  mutable int x;
};

int main()
{
  M xx;
  std::cout << xx.getX() << std::endl;
}

我不应该将getX声明为const吗?

Edit 1 (ForEver's answer makes the things more clear), the following code will not be compiled

class M
{
public:
  M(){x=10;};
  int getX() const {x++; return x;};
private:
  int x;
};

int main()
{
  M xx;
  std::cout << xx.getX() << std::endl;
}

3 回答

  • 3

    const 函数中修改mutable是合法的,当然修改 non-const 函数中的mutable是合法的(每个 non-const member-variable ) . mutable 关键字允许修改 const 函数中的变量,但不对 non-const 函数中的修改提供任何限制 .

  • 0

    mutable 通常用于允许 const 限定的成员函数修改缓存的数据 . 您可以将 getX() 声明为 const 并愉快地修改 x ,'s what mutable is for. However it'通常被认为是一个坏主意,可以修改成员函数中对象的内部状态's declaration says it doesn' t .

    例如,您有一个const成员函数,它根据容器的内容计算值 . 如果容器有很多元素,可能需要很长时间才能得到结果 . 如果结果仅在您从容器中添加或删除元素时发生更改,则可以将其缓存以供以后使用 . 由于成员函数是const限定的,因此您需要将结果变量声明为 mutable . 由于结果可以从容器中的现有数据计算,因此从const函数开始,缓存值被认为是可以修改它的 .

    int Foo::CalcResult() const
    {
        if(hasValidCache_ == false)
        {
    
            // ... recalc value ...
    
            // Cache the result
            hasValidCache = true;
            cachedValue_ result;
        }
    
        return cachedValue_;
    }
    
  • 0

    声明意味着这一点 .

    class M
    {
    public:
       M(){x=10;};
       int getX() const
     //           ^^^^^ If a member function is const...
    
                       {x++; return x;};
     //                 ^^^ ...and it modifies a member variable...
    private:
       mutable int x;
    // ^^^^^^^ ...then that variable must be mutable.
    };
    

相关问题