Aussie AI
Avoid temporary objects
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Avoid temporary objects
In the same way that temporary integer variables are used to compute an integer
expression, so too are temporary objects used in non-trivial expressions involving class
objects. For example, consider this code where the Complex
class has defined the +
and =
operators:
Complex c1,c2,c3; c1 = c2 + c3;
This is likely to create a temporary Complex object as the result of the addition, and this
temporary object is then passed as an operand to the =
operator. In other words, the
expression is actually evaluated as:
operator=( c1, operator+(c2, c3) );
A temporary object must be created to store the “+
” sub-expression computed for the second
argument, and then passed to the “=
” operator. Whether the operands to operator=
are passed by reference or by
value has no effect on whether a temporary is created in this situation (it will only
affect the creation of new objects inside the operator=
function).
One (rather inelegant) method of avoiding this creation of temporaries is to create a specialized function to handle it:
void AssignThree(Complex &c1, Complex &c2, Complex & c3); ... AssignThree(c1,c2,c3); // c1 = c2 + c3;
The function should probably be a friend
function to allow efficient access to the data
members of the three Complex
objects.
The problems with this solution are its very poor style (because the neatness of the
use of overloaded operators is lost), and also its non-general character. More complicated
expressions will still generate temporaries, unless more special functions are added as
friend
functions, leading to even worse style. This “cure” is perhaps worse than the disease.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |