< previous page page_189 next page >

Page 189
On line 25, the return of TheFunction() is assigned to a reference to a SimpleCat, and that object is used to obtain the cat's age, which is printed on line 27.
To prove that the reference declared in main() is referring to the object put on the free store in TheFunction(), the address of operator is applied to rCat. Sure enough, it displays the address of the object it refers to, and this matches the address of the object on the free store.
So far, so good. But how will that memory be freed? You can't call delete on the reference. One clever solution is to create another pointer and initialize it with the address obtained from rCat. This does delete the memory, and plugs the memory leak. One small problem, though: What is rCat referring to after line 31? As stated earlier, a reference 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.

There are actually three solutions to this problem. The first is to declare a SimpleCat object on line 25 and to return that cat from TheFunction() by value. The second is to go ahead and declare the SimpleCat on 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 function 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 imperative 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 will be 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.

 
< previous page page_189 next page >

If you like this book, buy it!