Aussie AI
Temporary Objects and Destruction
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Temporary Objects and Destruction
Temporary objects are created automatically by the compiler in a number of situations. This is a similar idea to that of a C++ compiler generating temporary values for intermediate results of a computation. However, a temporary with class type will have its constructor and destructor activated, so temporary objects can be quite expensive.
For example, try the following class to demonstrate
how a temporary object is defined for intermediate expression results, particularly that
returned by the +
operator:
#include <iostream.h> class Integer { private: int val; public: Integer() { val = 0; cout << "Constructor\n"; } ~Integer() { cout << "Destructor\n"; } Integer(const Integer &x) { val = x.val; cout << "Copy Constructor\n"; } void operator=(int x) { val = x; } void operator=(const Integer &x) { val = x.val; } friend Integer operator+(Integer &x, Integer &y); }; Integer operator+(Integer &x, Integer &y) { Integer temp; // user-defined temporary temp.val = x.val + y.val; return temp; // creates compiler temporary } int main() { Integer i, j, k; k = i + j; }
There are 4 calls to the ordinary constructor corresponding to i
, j
, k
, and temp
; there is
a single call to the copy constructor that occurs when the return
statement creates a
temporary object for the object returned from operator +
. This temporary object is the
result of i+j
and is then assigned to k
.
In this case there are poor performance and no errors related to temporary objects and in most cases, temporary objects are transparent to the programmer for a correctly defined class (i.e., having both assignment operator and copy constructor). However, if the programmer unwittingly stores a reference or pointer to members of a temporary object, there may be errors in a later use of the reference or pointer. The problem is that temporary objects can be destroyed by the compiler as soon as they have been used in the computation, and so the reference or pointer is no longer valid. However, since the timing of the destruction of temporaries is undefined, some compilers will not exhibit an error for such code because they leave the destruction of temporaries till late; it depends on how aggressively a particular compiler performs its internal code optimization.
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |