Home > OS >  C , operator [], and tracking a change
C , operator [], and tracking a change

Time:04-03

I'm trying to build a little array-ish class, like so:

class dumb
{
    bool mChanged=false;
    int mData[1000];
    int& operator [](int i) {return mData[i];}
};

Here's my question-- is there any kind of hack or trick I could do so that if I did this:

dumb aDumbStuff;
aDumbStuff[5]=25;  <- now mChanged gets set to true!

So basically, I want my class's mChanged value to go true if I modify any content. Any way to do this without making the array itself an array of objects that they themselves track getting changed, or by doing memcmps to see if things changed at all?

Some complex dance of assignment operators that would let my class detect "[n]=" happening?

CodePudding user response:

The usual solution is to use a helper class, something like:

struct inner_ref {
   dumb &me;
   int i;

   inner_ref(dumb &, int);

   operator int();

   dumb &operator=(int);
};

The operator[] overload returns this object, constructing it using a reference to *this, and the passed-in array index. Its operator= overload executes the actual assignment and also sets this flag. Its operator int() provides the appropriate semantics when [] is used to access the array's value, rather than modifying it.

CodePudding user response:

You could set the flag to 'changed' inside your existing operator[] method, and add a second version with const returning an int (= not as a reference):

int operator [](int i) const {return mData[i];}

The compiler would pick the right one - modifying or not, as needed!

  • Related