Home arrow C++ arrow Temporary Variables: Chasing Temporaries Away

Temporary Variables: Chasing Temporaries Away

There are situations in C++ when it is good to return the result of a function by value rather than by reference. There is usually a price to be paid, however...unless the compiler can be made to help. Jun Nakamura explains.

Author Info:
By: J. Nakamura
Rating: 5 stars5 stars5 stars5 stars5 stars / 5
October 10, 2005
  1. · Temporary Variables: Chasing Temporaries Away
  2. · Return Value Optimization
  3. · Vector3 test
  4. · Details, details… what’s that… small print?
  5. · Help the compiler help you

print this article

Temporary Variables: Chasing Temporaries Away
(Page 1 of 5 )

>There are only two qualities in the world: efficiency and inefficiency.

>And only two sorts of people: the efficient and the inefficient.

 (G. Bernard Shaw 1856-1950)

Finding the Closest Enemy

In the previous article we discovered that there are situations where it is beneficial to return the result of a function by value. The example used was the subtraction operator implemented for a Vector3 class:

class Vector3 {
 float mX, mY, mZ;
      Vector3 const operator– (Vector3 const &rhs) const {
  return Vector3(mX-rhs.mX, mY-rhs.mY, mZ-rhs.mZ);

This operator is needed to determine a vector between two points, where the length of the vector determines the distance between the two points. It is not possible for this function to return a reference one way or the other, so it has to return the result by value.

What we are going to examine now is how we can help the compiler to optimize the temporary variable away, so we won’t have pay a price for returning by value at all!

blog comments powered by Disqus

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials