const
ObjectThe usual reason for using a const
reference is efficiency, but there are restrictions on when this choice can be used. If a function returns an object that is passed to it, either by object invocation or as a method argument, you can increase the efficiency of the method by having it return a reference. For example, suppose you wanted to write a function Max()
that returned the larger of two Vector
objects, where Vector
is the class developed in Chapter 11. The function would be used in this manner:
Vector force1(50,60);
Vector force2(10,70);
Vector max;
max = Max(force1, force2);
Either of the following two implementations would work:
// version 1
Vector Max(const Vector & v1, const Vector & v2)
{
if (v1.magval() > v2.magval())
return v1;
else
return v2;
}
// version 2
const Vector & Max(const Vector & v1, const Vector & v2)
{
if (v1.magval() > v2.magval())
return v1;
else
return v2;
}
There are three important points here. First, recall that returning an object invokes the copy constructor, whereas returning a reference doesn’t. Thus Version 2 does less work and is more efficient. Second, the reference should be to an object that exists when the calling function is executing. In this example, the reference is to either force1
or force2
, and both are objects defined in the calling function, so this requirement is met. Third, both v1
and v2
are declared as being const
references, so the return type has to be const
to match.
3.21.106.7