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?
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:
If you do it the other way around, the last copy is eliminated:
Therefore, using the compound addition-assignment in the implementation of the binary +
is more efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With