A temporary object is an unnamed intermediary created while evaluating an expression. It holds a partial result, then is destroyed after serving its purpose. Unnecessary temporaries add constructor and destructor calls, so recognizing them is a practical performance and maintenance skill. section 9.0 section 9.9
A common mistake is returning a value from a copy assignment operator when the operation has already updated its target. The returned copy becomes a temporary, even though chained assignment only needs a reference to the updated object. section 9.4
Watch for temporaries in these situations:
- Returning a newly constructed object from copy assignment creates and discards an extra object; return a reference and return *this instead. section 9.4
- Writing c1 + c2 + c3 can create one temporary for c1 + c2 and another for the next sum before initializing c4. section 9.9
- Use compound assignment to modify an existing result, either directly or inside operator+, when that preserves the intended interface. section 9.9
- Modern C++ also provides rvalue references for more efficient handling of temporary objects, but the examples focus on simpler operator changes. section 2.0
Complex-number assignment and addition
The problematic assignment constructs a local Complex object, copies its values into the target, and returns that local object. A safer form assigns directly from the parameter and returns Complex& with return *this. For arithmetic, c4 = c1 + c2 + c3 creates intermediate results; alternatively, initialize c4 from c1 and apply c4 += c2 and c4 += c3.
Listing 9.23 Class with minimized temporaries in expression evaluation
class Complex {
private:
double real;
double imag;
public:
Complex(double real=0, double imag=0) : real(real), imag(imag) {}
Complex& operator+=(const Complex&);
double getReal() const { return real; }
double getImag() const { return imag; }
};
Complex& Complex::operator+=(const Complex& o) { #1
real += o.real;
imag += o.imag;
return *this;
}
const Complex operator+(const Complex& lhs, const
Complex& rhs) { #2
return Complex(lhs) += rhs;
}
int main() {
Complex c1(2, 2);
Complex c2(0, -1);
Complex c3(-2.2, 4.2);
Complex c4 = c1 + c2 + c3;
}
Compare an operator+ implementation built from operator+= with the version that constructs a result directly. section 9.9

