1

我正在研究 C++,我读到:如果一个数据成员被声明为可变的,那么从一个 const 成员函数为这个数据成员赋值是合法的。 但是以下代码编译时没有任何错误或 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 吗?

编辑1(ForEver的回答让事情更清楚了),以下代码将不会被编译

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

3 回答 3

3

在函数中修改可变变量const是合法的,当然在函数中修改可变变量也是合法的non-const(如 each non-const member-variable)。mutable关键字允许在const函数中修改变量,但对函数中的修改没有任何限制non-const

于 2013-04-25T05:01:52.660 回答
0

mutable is typically used to allow const qualified member functions to modify cached data. You can declare getX() as const and happily modify x, that's what mutable is for. However it's generally considered a bad idea to modify the internal state of an object in a member function that by it's declaration says it doesn't.

For example, you have a const member function that calculates a value based on the contents of a container. If the container has a lot of elements it might take a long time to get the result. If the result only changes when you add or remove elements from the container you could cache it for later use. Since the member function is const qualified you would need to declare the result variable as mutable. Since the result can be calculated from the existing data in the container the cached value isn't considered part of the internal state of the object and it's considered OK to modify it since of a const function.

int Foo::CalcResult() const
{
    if(hasValidCache_ == false)
    {

        // ... recalc value ...

        // Cache the result
        hasValidCache = true;
        cachedValue_ result;
    }

    return cachedValue_;
}
于 2013-04-25T05:22:32.387 回答
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.
};
于 2013-04-25T05:28:50.920 回答