Click here to Skip to main content
Click here to Skip to main content

Tagged as

C++ Tip : How to eliminate Temporary Objects

, 23 Aug 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
C++ creates temporary objects "behind your back" in several contexts. The overhead of a temporary can be significant because both its constructor and destructor are invoked. You can prevent the creation of a temporary object in most cases, though. In the following example, a temporary is created:
Complex x, y, z;
x=y+z; /* temporary created */
The expression y+z; results in a temporary object of type Complex that stores the result of the addition. The temporary is then assigned to x and destroyed subsequently. The generation of the temporary object can be avoided in two ways:
Complex y,z;
Complex x=y+z; /* initialization instead of assignment */
In the example above, the result of adding x and z is constructed directly into the object x, thereby eliminating the intermediary temporary. Alternatively, you can use += instead of + to get the same effect:
/* instead of x = y+z; */  
x=y;  
x+=z; 

Although the += version is less elegant, it costs only two member function calls: assignment operator and operator +=. In contrast, the use of + results in three member function calls: a constructor call for the temporary, a copy constructor call for x, and a destructor call for the temporary.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

elitehussar

United States United States
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150128.1 | Last Updated 23 Aug 2010
Article Copyright 2010 by elitehussar
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid