Lecture 2 - Slide 17 : 29
Lvalue References versus Pointers
Examples that compare programming with pointers and C++ references in the
swap
function
Two versions of swap - with references and with pointers.
Observations
The notational overhead - use of
&
and
*
- is less for use of references than for pointers
The reason is that it is not possible to manipulate the reference as such
The mental models are different
Pointers: Establish a pointer to an object, follow the pointer to the object for lhs/rhs access.
The pointer itself may be accidentally changed.
References: Establish an alternative name to an existing object (an
alias
).
Once established the reference can never be changed.
The C++ Prog. Lang. (4. edition)
: Page 189
A reference may be implemented as a
constant pointer
that is dereferenced automatically each time it is used