Const correctness pains

Started by
2 comments, last by popsoftheyear 15 years, 9 months ago
So, I've got a class that, when only using an instance of it to read relavent data, I pass a const reference to whatever function uses it. However, the "read only" member function actually writes to the class... so how can I implement the following, and allow const correctness? MUST I used a const_cast? I shy away from this. I thought about just making LastX and LastY static... but that would render this thing not very multithreaded friendly... Maybe the flaw is in what I am doing?
class IAmUseful {
public:
  int *CalcAPointer(int X, int Y) const {
    if (LastX_ != X || LastY != Y) {
      LastX_ = X;
      LastY_ = Y;
      LastPointer_ = SomeStuffBasedOnXAndY;
    }
    return LastPointer_;
  }
private:
  int LastX_, LastY_
  int *LastPointer_;
};

--------
// At some point in the code that uses it
void ThisUsesIt(const IAmUseful &UsefulObj, int A, int B) {
  int *NewPointer = UsefulObj.CalcAPointer(A, B);
  // Doesn't matter what I do here because we now have const problems.
  // Not to mention the class probably wouldn't compile either huh?
}

Cheers -Scott
Advertisement
Well in your case the function isn't const at all since it seems to be iterative in nature. If you really want to do it you have the mutable keyword which you can apply on your members in order to make them changeable from const methods.
blandishment
I know asp_... but my actual function is a bit more complex than that doesn't guarantee any consistent iterative pattern. Anyway thanks to the both of you... I'm glad I learned this!

Cheers
-Scott

This topic is closed to new replies.

Advertisement