跟踪c ++类中的跟踪更改

And*_*eas 1 c++

将用一个简单的例子来解释这一点.

class Vector
{
    float X;
    float Y;
    float _length;
    float Length();
}
Run Code Online (Sandbox Code Playgroud)

我只计算长度,如果X或Y改变,则将其分配给_length.如果它们都没有改变我只是简单地返回_length.

Jef*_*eff 5

您需要在标记X/ Y修改时包含一个保护标志(或"无效"值):

class Vector {
 public:
  Vector(float x = 0.0, float y = 0.0)
  : X{x}, Y{y}, Length{-1.0f}
  { }

  float x() const { return X; }
  float y() const { return Y; }

  float length() const {
    if (Length < 0.0f) {
      Length = sqrt(X*X + Y*Y);
    }
    return Length;
  }

  void setX(float x) { if (X != x) { Length = -1.0f; } X = x; }
  void setY(float y) { if (Y != y) { Length = -1.0f; } Y = y; }

 private:
  float X;
  float Y;
  mutable float Length;
};
Run Code Online (Sandbox Code Playgroud)

所述mutable限定词是指那些值不是一个对象的"逻辑"状态的一部分,并且可以在一个甚至改性const的实例Vector(通过const成员函数,天然地).

  • @Zaiborg 这就像`mutable`的*唯一*使用,这种记忆问题是极少数用例之一。 (2认同)