Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it more efficient to define operator+ to call operator+= rather than the other way around?

It's an exercise from C++ Primer 5th Edition:

Exercise 14.14: Why do you think it is more efficient to define operator+ to call operator+= rather than the other way around?(P.561)

Given the implementations for operator+= and operator+:

Sales_data& 
Sales_data::operator+=(const Sales_data &rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}

Sales_data
operator+(const Sales_data &lhs, const Sales_data &rhs)
{
    Sales_data sum = lhs;  // copy data members from lhs into sum
    sum += rhs;             // add rhs into sum
    return sum;
}

At the end of this section (14.3) , the author gave a tip that

Classes that define both an arithmetic operator and the related compound assignment ordinarily ought to implement the arithmetic operator by using the compound assignment.

Can anyone explain this tip, using facts/examples?

like image 1000
Yue Wang Avatar asked Jan 12 '14 04:01

Yue Wang


1 Answers

The reason is in the number of copying that needs to be made: binary operator + creates and returns a new object that represents a sum, while the compound addition-assignment operator modifies the object in place.

If you would like to implement the compound operator in terms of the binary operator, the sequence of actions would be as follows:

  • Compound assignment calls the binary operator
  • The binary operator creates a new object from one of the objects (copy #1), and puts the sum into it
  • The sum is returned by value (copy #2)
  • The sum object is copied into the object on the left-hand side object (copy #3)

If you do it the other way around, the last copy is eliminated:

  • Binary operator creates an object representing the sum from the left-hand side object
  • Binary operator invokes the compound addition-assignment, which does not require copying
  • Binary operator returns the object by value (copy #2)

Therefore, using the compound addition-assignment in the implementation of the binary + is more efficient.

like image 187
Sergey Kalinichenko Avatar answered Sep 28 '22 06:09

Sergey Kalinichenko