In C, if a function needs to modify a variable, the parameter must use a pointer, eg
int foo(int *pval). In C++, the function can alternatively declare a reference parameter:
int foo(int &val).
Pros:Defining a parameter as reference avoids ugly code like
(*pval)++. Necessary for some applications like copy constructors. Makes it clear, unlike with pointers, that a null pointer is not a possible value.
Cons:References can be confusing, as they have value syntax but pointer semantics.
Within function parameter lists all references must be
In fact it is a very strong convention in Google code that input arguments are values or
void Foo(const string &in, string *out);
const references while output arguments are pointers. Input parameters may be
const pointers, but we never allow non-
const reference parameters.However, there are some instances where using
const T* is preferable to
const T& for input parameters. For example:
Remember that most of the time input parameters are going to be specified as
- You want to pass in a null pointer.
- The function saves a pointer or reference to the input.
const T&. Using
const T* instead communicates to the reader that the input is somehow treated differently. So if you choose
const T* rather than
const T&, do so for a concrete reason; otherwise it will likely confuse readers by making them look for an explanation that doesn't exist.