When to Use Reference Arguments

C++ Primer Plus

There are two main reasons for using reference arguments:

  • To allow you to alter a data object in the calling function
  • To speed up a program by passing a reference instead of an entire data object

The second reason is most important for larger data objects, such as structures and classobjects.These two reasons are the same reasons you might have for using a pointer argu-ment.This makes sense because reference arguments are really just a different interface for
pointer-based code. So when should you use a reference? Use a pointer? Pass by value?The following are some guidelines.

A function uses passed data without modifying it:

  • If the data object is small, such as a built-in data type or a small structure, pass itby value.
  • If the data object is an array, use a pointer because that’s your only choice. Make thepointer a pointer to const.
  • If the data object is a good-sized structure, use a const pointer or a const referenceto increase program efficiency.You save the time and space needed to copy a struc-ture or a class design. Make the pointer or reference const.
  • If the data object is a class object, use a const reference.The semantics of classdesign often require using a reference, which is the main reason C++ added thisfeature.Thus, the standard way to pass class object arguments is by reference.

A function modifies data in the calling function:

  • If the data object is a built-in data type, use a pointer. If you spot code like
    fixit(&x), where x is an int, it’s pretty clear that this function intends to modify x.
  • If the data object is an array, use your only choice: a pointer.
  • If the data object is a structure, use a reference or a pointer.
  • If the data object is a class object, use a reference.

Of course, these are just guidelines, and there might be reasons for making differentchoices. For example, cin uses references for basic types so that you can use cin >> ninstead of cin >> &n.

你可能感兴趣的:(When to Use Reference Arguments)