Why return by reference?

Return by reference is typically used to return arguments passed by reference to the function back to the caller. In the following example, we return (by reference) an element of an array that was passed to our function by reference:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
struct FixedArray25
{
    int anValue[25];
};
 
// Returns a reference to the nIndex element of rArray
int& Value(FixedArray25 &rArray, int nIndex)
{
    return rArray.anValue[nIndex];
}
 
int main()
{
    FixedArray25 sMyArray;
 
    // Set the 10th element of sMyArray to the value 5
    Value(sMyArray, 10) = 5;
 
    cout << sMyArray.anValue[10] << endl;
    return 0;
}

# standard output:
5


But why? Why return a reference to an integer, when you can just return an integer by value. What is the whole reasoning behind the design decision of allowing you to return by reference?
Return by reference is used when you want a read-write copy of some data i.e. you can change the value of the variable in question , while with return by value you get a read-only copy.
Return by reference allows this
 
Value(5) = 42;

So it is an lvalue.
Just like when you pass a value, when you return a value from a function, you're really returning a copy of that value. It can be expensive operation if you're returning a large object. Returning a reference is an efficient alternative. Passing by reference will give you direct access to the argument variable without having to copy it, you could use a constant reference to avoid altering the variable, so it's like providing a read-only access.

You could also achieve the same thing with pointers, however, a reference provides cleaner syntax.
Last edited on
Topic archived. No new replies allowed.