|
|
|
|
|
|
|
The output is identical to that produced by Listing 12.2. The only significant change is that FunctionTwo() now takes and returns a reference to a constant object. Once again, working with references is somewhat simpler than working with pointers; and the same savings and efficiency, as well as the safety provided by using const, is achieved. |
|
|
|
|
|
|
|
|
When to Use References and When to Use Pointers |
|
|
|
|
|
|
|
|
C++ programmers strongly prefer references to pointers. References are cleaner and easier to use, and they do a better job of hiding information, as you saw in the previous example. |
|
|
|
|
|
|
|
|
References cannot be reassigned, however. If you need to point first to one object and then to another, you must use a pointer. References cannot be null, so if there is any chance that the object in question might be null, you must not use a reference. You must use a pointer. |
|
|
|
|
|
|
|
|
An example of the latter concern is the operator new. If new cannot allocate memory on the free store, it returns a null pointer. Because a reference can't be null, you must not initialize a reference to this memory until you've checked that it is not null. The following example shows how to handle this: |
|
|
|
|
|
|
|
|
int *pInt = new int;
if (pInt != NULL)
int &rInt = *pInt; |
|
|
|
|
|
|
|
|
In this example, a pointer to int, pInt, is declared and initialized with the memory returned by the operator new. The address in pInt is tested, and if it is not null, pInt is dereferenced. The result of dereferencing an int variable is an int object, and rInt is initialized to refer to that object. Thus, rInt becomes an alias to the int returned by the operator new. |
|
|
|
|
|
|
|
|
Don't Return a Reference to an Object that Isn't in Scope! |
|
|
|
|
|
|
|
|
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 sure to ask yourself, What is the object I'm aliasing, and will it still exist every time it's used? |
|
|
|
|
|