References vs Pointers
It's good to know when to use references vs using pointers.
Full text can be found here: http://cs-people.bu.edu/dbuzan/cs112/lab4a/lab2.html
Our suggestions for the usage of references as arguments to functions
are therefore the following:
-
In those situations where a called function does not alter its arguments,
a copy of the variable can be passed.
-
When a function changes the value of its argument, the address or a reference
can be passed, whichever you prefer.
-
References have an important role in those cases where the argument will
not be changed by the function, but where it is desirable to
pass a reference to the variable instead of a copy of the whole variable.
Such a situation occurs when a large variable, e.g., a struct, is passed
as argument, or is returned from the function. In these cases the copying
operations tend to become significant factors when the entire structure
must be copied, and it is preferred to use references. If the argument
isn't changed by the function, or if the caller shouldn't change the returned
information, the use of the const keyword is appropriate and should be
used.
A number of differences between pointers and references is pointed out
in the list below:
-
A reference cannot exist by itself, i.e., without something to refer to.
-
References can, however, be declared as external. These references were
initialized elsewhere.
-
Reference may exist as parameters of functions: they are initialized when
the function is called.
-
References may be used in the return types of functions. In those cases
the function determines to what the return value will refer.
-
Reference may be used as data members of classes.
-
In contrast, pointers are variables by themselves. They point at something
concrete or just ``at nothing''.
-
References are aliases for other variables and cannot be re-aliased to
another variable. Once a reference is defined, it refers to its particular
variable.
-
In contrast, pointers can be reassigned to point to different variables.
-
When an address-of operator & is used with a reference, the expression
yields the address of the variable to which the reference applies. In contrast,
ordinary pointers are variables themselves, so the address of a pointer
variable has nothing to do with the address of the variable pointed to.
- http://cs-people.bu.edu/dbuzan/cs112/lab4a/lab2.html