Exploiting References 285
9
So far, so good. But how will that memory be freed? You can’t call delete on the refer-
ence. One clever solution is to create another pointer and initialize it with the address
obtained from rCat. This does delete the memory, and it plugs the memory leak. One
small problem, though: What is rCatreferring to after line 34? As stated earlier, a refer-
ence must always alias an actual object; if it references a null object (as this does now),
the program is invalid.
It cannot be overemphasized that a program with a reference to a null
object might compile, but it is invalid and its performance is unpredictable.
NOTE
Three solutions exist to this problem. The first is to declare a SimpleCatobject on line
28 and to return that cat from TheFunction()by value. The second is to go ahead and
declare the SimpleCaton the free store in TheFunction(), but have TheFunction()
return a pointer to that memory. Then, the calling function can delete the pointer when it
is done.
The third workable solution, and the right one, is to declare the object in the calling func-
tion and then to pass it to TheFunction()by reference.
Pointer, Pointer, Who Has the Pointer? ..............................................................
When your program allocates memory on the free store, a pointer is returned. It is imper-
ative that you keep a pointer to that memory because after the pointer is lost, the memory
cannot be deleted and becomes a memory leak.
As you pass this block of memory between functions, someone will “own” the pointer.
Typically, the value in the block is passed using references, and the function that created
the memory is the one that deletes it. But this is a general rule, not an ironclad one.
It is dangerous for one function to create memory and another to free it, however.
Ambiguity about who owns the pointer can lead to one of two problems: forgetting to
delete a pointer or deleting it twice. Either one can cause serious problems in your pro-
gram. It is safer to build your functions so that they delete the memory they create.
If you are writing a function that needs to create memory and then pass it back to the
calling function, consider changing your interface. Have the calling function allocate the
memory and then pass it into your function by reference. This moves all memory man-
agement out of your program and back to the function that is prepared to delete it.