Reference (C++) - Uses of References

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:
void square(int x, int& result) { result = x * x; }

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:

square(3, 6);
  • Returning a reference allows function calls to be assigned to:
int& preinc(int& x) { return ++x; // "return x++;" would have been wrong } preinc(y) = 5; // same as ++y, y = 5
  • 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:
void f_slow(BigObject x) { /* ... */ } void f_fast(const BigObject& x) { /* ... */ } BigObject y; f_slow(y); // slow, copies y to parameter x f_fast(y); // fast, gives direct read-only access to y

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++)