The return optimization
When new objects are created to return by
value, notice the form used. In operator+, for example:
return Integer(left.i + right.i);
This may look at first like a
“function call to a constructor,” but it’s not. The syntax is
that of a temporary object; the statement says “make a temporary
Integer object and return it.” Because of this, you might think
that the result is the same as creating a named local object and returning that.
However, it’s quite different. If you were to say
instead:
Integer tmp(left.i + right.i);
return tmp;
three things will happen. First, the
tmp object is created including its constructor call. Second, the
copy-constructor copies the tmp to the location
of the outside return value. Third, the destructor is called for tmp at
the end of the scope.
In contrast, the “returning a
temporary” approach works quite differently. When
the compiler sees you do this, it knows that you have no other need for the
object it’s creating than to return it. The compiler takes advantage of
this by building the object directly into the location of the outside
return value. This requires only a single ordinary constructor call (no
copy-constructor is necessary) and there’s no destructor call because you
never actually create a local object. Thus, while it doesn’t cost anything
but programmer awareness, it’s significantly more efficient. This is often
called the return value
optimization.