The reference argument in
Reference.cpp works only when the argument is a non-const object.
If it is a const object, the function g( ) will not accept
the argument, which is actually a good thing, because the function does
modify the outside argument. If you know the function will respect the
constness of an object, making the argument a
const reference will allow the function to be
used in all situations. This means that, for built-in types, the function will
not modify the argument, and for user-defined types, the function will call only
const member functions, and won’t modify any public data
members.
The use of const references in
function arguments is especially important because your function may receive a
temporary
object. This might have been
created as a return value of another function or explicitly by the user of your
function. Temporary objects are always const, so if you don’t use a
const reference, that argument won’t be accepted by the compiler.
As a very simple example,
The call to f(1) causes a
compile-time error because the compiler must first create a reference. It does
so by allocating storage for an int, initializing it to one and producing
the address to bind to the reference. The storage must be a const
because changing it would make no sense – you can never get your hands on
it again. With all temporary objects you must make the same assumption: that
they’re inaccessible. It’s valuable for the compiler to tell you
when you’re changing such data because the result would be lost
information.