1

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; to avoid the creation of a temporary object is not acceptable in my case.

Michael M.
  • 2,556
  • 1
  • 16
  • 26
  • `_Data` is a [reserved identifier](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). – chris Aug 14 '13 at 10:53
  • `std::transform` should be able to do this. – chris Aug 14 '13 at 10:54
  • You could make the assignment cheap with a move assignment operator. – juanchopanza Aug 14 '13 at 10:56
  • C++11 makes this ceaper with move I tink. – user2672165 Aug 14 '13 at 10:57
  • You can write your own function like AddAndAssign(c,a,b), but not bind binary operators like ternary. But better just use move constructor and move assigment operator. – user1837009 Aug 14 '13 at 11:00
  • 1
    Off-topic, but don't forget the [Rule of Three](http://stackoverflow.com/questions/4172722) when you mess around with low-level memory management. Better still, follow the Rule of Zero: `std::vector data;`. Also, you shouldn't use [reserved names](http://stackoverflow.com/questions/228783) like `_Data`. – Mike Seymour Aug 14 '13 at 11:22

1 Answers1

1

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.

dhavenith
  • 2,028
  • 13
  • 14