Sams Teach Yourself C++ in 21 Days

(singke) #1
Exploiting References 281

9


The counterargument is that the type is Cat. The &is part of the “declarator,” which
includes the variable name and the ampersand. More important, having the &near the
Catcan lead to the following bug:
Cat& rFrisky, rBoots;
Casual examination of this line would lead you to think that both rFriskyand rBoots
are references to Catobjects, but you’d be wrong. This really says that rFriskyis a ref-
erence to a Cat, and rBoots(despite its name) is not a reference but a plain old Catvari-
able. This should be rewritten as follows:
Cat &rFrisky, rBoots;
The answer to this objection is that declarations of references and variables should never
be combined like this. Here’s the right way to declare the reference and nonreference
variable:
Cat& rFrisky;
Cat boots;
Finally, many programmers opt out of the argument and go with the middle position, that
of putting the &in the middle of the two, as illustrated in case 2.
Of course, everything said so far about the reference operator (&) applies equally well to
the indirection operator (*). The important thing is to recognize that reasonable people
differ in their perceptions of the one true way. Choose a style that works for you, and be
consistent within any one program; clarity is, and remains, the goal.

Many programmers like the following conventions for declaring references
and pointers:


  • Put the ampersand and asterisk in the middle, with a space on either
    side.

  • Never declare references, pointers, and variables all on the same line.


NOTE


Returning Out-of-Scope Object References ........................................................


After C++ programmers learn to pass by reference, they have a tendency to go hog-wild.
It is possible, however, to overdo it. Remember that a reference is always an alias to
some other object. If you pass a reference into or out of a function, be certain to ask
yourself, “What is the object I’m aliasing, and will it still exist every time it’s used?”
Listing 9.13 illustrates the danger of returning a reference to an object that no longer
exists.
Free download pdf