Uses of References
- Other than just a helpful replacement for pointers, one convenient application of references is in function parameter lists, where they allow passing of parameters used for output with no explicit address-taking by the caller. For example:
Then, the following call would place 9 in y:
square(3, y);However, the following call would give a compiler error, since reference parameters not qualified with const
can only be bound to addressable values:
- Returning a reference allows function calls to be assigned to:
- In many implementations, normal parameter-passing mechanisms often imply an expensive copy operation for large parameters. References qualified with
const
are a useful way of passing large objects between functions that avoids this overhead:
If f_fast
actually requires its own copy of x that it can modify, it must create a copy explicitly. While the same technique could be applied using pointers, this would involve modifying every call site of the function to add cumbersome address-of (&
) operators to the argument, and would be equally difficult to undo, if the object became smaller later on.
Read more about this topic: Reference (C++)