Problem |
Intermediate temporary variables are used only as middlemen in computations.
|
Context |
End-game optimization of a program that makes heavy use of algebraic types.
|
Forces |
You want operator+ and operator+= to have properly related
semantics, so you want to implement one in terms of the
other. The outside user doesn't care which derives from the
other. Temporary variables can be expensive, particularly for
large algebraic types (e.g., large arrays).
|
Solution |
Define operator+ in terms of operator+=, not the other
way around. Define other arithmetic operators analogously.
|
Example |
Not:
Complex operator+ (const Complex &a1, const Complex &a2) { Complex result = a1; result.rpart += a2.rpart; result.ipart += a2.ipart; return result; } Complex& Complex::operator+= (const Complex &a1) { Complex temporary = *this + a1; *this = temporary; }But: Complex& Complex::operator+= (const Complex &al) { rpart += al.rpart; ipart += al.ipart; return *this; // no new object } Complex operator+ (const Complex &al, const Complex &a2 { Complex retval = al; retval += a2; return retval; }
|
Resulting context | Saves a lot of memory and time for large algebraic types like arrays or strings. |
[Source: James Coplien, "After all, we can't ignore efficiency", C++ Report, May 96, p69] |