Temporary Variables: Chasing Temporaries Away
(Page 1 of 5 )
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.>
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;
public:
...
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!
Next: Return Value Optimization >>
More C++ Articles
More By J. Nakamura