Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++, operator [], and tracking a change

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading