Re: Function arguments: References vs pointers
void f(int& i)
{
i = 1;
}
void g(int* j)
{
*j = 2;
}
<snip>
Except for the source code being easier to read by the human
when using references, are there more differences between the
two forms?
You would generally use a reference parameter when you require that
the object it refers to MUST exist for the function to operate
correctly. By using a reference instead of a pointer, you are
communicating to the caller that a valid object must be provided. If
the function accepted a pointer instead, then you are relying on the
caller having read your documentation to understand that a non-null
parameter must be supplied. Better to make the code make this
explicitly clear and use a reference.
Note that it is still possible to provide a reference to an object
which no longer exists (eg you explicitly delete the object the
reference refers to before calling the function), but there's not much
you can do about that. The caller is responsible for ensuring that the
reference it passes is still valid. Still, using a reference instead
of a pointer when the object being referred to must exist is the
clearest way to say (in code) to clients what the function requires of
its arguments.
The advice of FAQ 8.6 is also good here: "Use references where you
can, pointers where you have to.". The following URL is provided for
convenience:
http://www.parashift.com/c++-faq-lite/references.html#faq-8.6
--
Computational Fluid Dynamics, CSIRO (CMIS)
Melbourne, Australia
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]