Aussie AI
Avoid temporaries via extra member functions
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Avoid temporaries via extra member functions
There are situations where the removal of temporaries does not lead to poor style.
Consider the following definition of a minimal Complex
class:
class complex { private: double re; // real part double im; // imaginary part public: // Constructors complex() { re = 0.0; im = 0.0; } complex(double r) { re = r; im = 0.0; } complex(double r, double i) { re = r; im = i; } // Copy constructor complex(complex &c) { re = c.re; im = c.im; } // Overloaded assignment operator void operator = (complex & d) { re = d.re; im = d.im; } // Overloaded + operator friend complex operator + (complex &c1, complex &c2); }; inline complex operator + (complex &c1, complex &c2) { return complex(c1.re + c2.re, c1.im + c2.im); }
Consider this class definition when used in the following code sequence:
complex c1, c2; c1 = 2.0; c2 = c1 + 3.0;
The effect is identical to:
c1 = complex(2.0); // invoke "double" constructor for 2.0 c2 = c1 + complex(3.0); // invoke "double" constructor for 3.0
The C++ compiler automatically creates two temporary objects from the double
constants, and calls the double
constructor to do so. The inefficiency of the creation of
a temporary object and the call to the constructor can be avoided by adding a few more
functions to the class declaration:
void operator = (double d) { re = d; im = 0.0; } friend complex operator + (double d, complex &c2); friend complex operator + (complex &c1, double d);
If these functions are present, then the double
constants are passed directly to the
double
parameters of these functions. No temporary object is created, and hence the
constructor is not called. Note that two symmetric versions of operator+
are required
because the C++ compiler cannot assume that the commutativity of +
holds for user-defined class objects.
By making the “interface” efficient for mixing complex and double variables, the
creation of temporaries has been reduced. This can be generalized: it is better to provide
member or friend
functions to class X
for a specific parameter type Y
, than to provide
only a constructor to create new X
’s from Y
’s.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |