C++ Programming Guide

Avoiding Temporary Objects

C++ functions often produce many implicit temporary objects, each of which must be created and destroyed. For non-trivial classes, this creation and destruction can get expensive. The Sun C++ compiler does eliminate some temporary objects, but it cannot eliminate all of them.

Write functions to minimize the number of temporary objects as long as your programs remain comprehensible. Techniques include using explicit variables rather than implicit temporary objects and using reference parameters rather than value parameters. Another technique is to implement and use operations such as += rather than implementing and using only + and =. For example, the first line below introduces a temporary object for the result of a + b, while the second line does not.


T x = a + b;
T x( a ); x += b;