简体   繁体   中英

Is it possible to use the modified returned reference in an overload like `int &operator[]'?

Suppose I have a class that implements an array of int which grows on demand. The class also implements the int &operator[] method overloading the [] operator and returning a reference to a value in the array.

Now I use the operator in a loop like this

classInstance[index] += 1;

I want to know whether it's possible to use the incremented value inside the int &operator[] function?

To make it clear, what I want is to be able to know what the new value of the referenced integer is in order to upadte the maximum and minimum values.

The way to solve this problem would be to return something that pretends to be an int& , while itself providing overloads for methods like operator+= , etc.

Something like this:

class MyIntReference {
 public:
  MyIntReference(int& reference_to_wrap) :
    wrapped_reference_{reference_to_wrap}
  {}

  // this method returns void, but you could have it return whatever you want
  void operator+=(const int addend) {
    wrapped_reference_ += addend;
    DoWhateverYouWant();
  }

 private:
  int& wrapped_reference_;
}

// then, in your other class
MyIntReference YourOtherClass::operator[](const int index) {
  return MyIntReference{my_array_[index]};
}

Obviously, this is just a rough piece of code, but I think it could be refined into something quite nice.

You could use Execute-Around Pointer idiom . Your operator[] would need to return a proxy object of a class that implements the necessary operations. Then you could "do something" in the destructor of the proxy object or immediately after the operations in their implementations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM