简体   繁体   中英

Overload operator in C++

Let say I have a class :

class MyIntegers
{
public:
  MyIntegers(int sz); //allocate sz integers in _Data and do some expensive stuff
  ~MyIntegers();      //free array

  int* _Data;
}

And this small piece of code :

int sz = 10;
MyIntegers a(sz), b(sz), c(sz);

for (int i=0; i<sz; i++)
{
  c._Data[i] = a._Data[i] + b._Data[i];
}

Is it possible to overload a ternary operator+ to replace the loop with c=a+b without create a temporary object ?

Overload the operator= and operator+= and write c=a; c+=b; c=a; c+=b; to avoid the creation of a temporary object is not acceptable in my case.

What you're looking for is called expression templates where basically an expression a+b does not lead to calculation of the result, but instead returns a 'proxy' object where the operation (+ in this case) is encoded in the type. Typically when you need the results, for instance when assigning to a variable, the operations that were encoded in the proxy type are used to do the actual calculation.

With C++11s move assignment operators there is less need for expression templates to optimize simple expressions with only one temporary (because that temporary will be moved to the final result), but it is still a technique to avoid big temporaries.

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