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.

6
  • _Data is a reserved identifier. Commented Aug 14, 2013 at 10:53
  • std::transform should be able to do this. Commented Aug 14, 2013 at 10:54
  • You could make the assignment cheap with a move assignment operator. Commented Aug 14, 2013 at 10:56
  • C++11 makes this ceaper with move I tink. Commented Aug 14, 2013 at 10:57
  • 1
    Off-topic, but don't forget the Rule of Three when you mess around with low-level memory management. Better still, follow the Rule of Zero: std::vector<int> data;. Also, you shouldn't use reserved names like _Data. Commented Aug 14, 2013 at 11:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.