Jump to content
  • Advertisement
Sign in to follow this  
popsoftheyear

Const correctness pains

This topic is 3645 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!