|
|
|
|
|
|
|
This program won't compile on the Borland compiler. It will compile on Microsoft compilers; however, it should be noted that this is a bad coding practice. |
|
|
|
|
|
|
|
|
|
Analysis: On lines 717, SimpleCat is declared. On line 26, a reference to SimpleCat is initialized with the results of calling TheFunction(), which is declared on line 22 to return a reference to a SimpleCat. |
|
|
|
|
|
|
|
|
The body of TheFunction() declares a local object of type SimpleCat and initializes its age and weight. It then returns that local object by reference. Some compilers are smart enough to catch this error and won't let you run the program. Other will let you run the program, but with unpredictable results. |
|
|
|
|
|
|
|
|
When TheFunction() returns, the local object, Frisky, will be destroyed (painlessly, I assure you). The reference returned by this function will be an alias to a nonexistent object, and this is a bad thing. |
|
|
|
|
|
|
|
|
Returning a Reference to an Object on the Heap |
|
|
|
|
|
|
|
|
You might be tempted to solve the problem in Listing 12.4 by having TheFunction() create Frisky on the heap. That way, when you return from TheFunction(), Frisky will still exist. |
|
|
|
|
|
|
|
|
The problem with this approach is: What do you do with the memory allocated for Frisky when you are done with it? Listing 12.5 illustrates this problem. |
|
|
|
|
|
|
|
|
LISTING 12.5 MEMORY LEAKS |
|
|
|
 |
|
|
|
|
1: // Listing 12.5
2: // Resolving memory leaks
3: #include <iostream.h>
4:
5: class SimpleCat
6: {
7: public:
8: SimpleCat (int age, int weight);
9: ~SimpleCat() {}
10: int GetAge() const { return itsAge; } |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|