Sams Teach Yourself C++ in 21 Days

(singke) #1
Exploiting References 283

9


On lines 7–17,SimpleCatis declared. On line 29, a reference to a SimpleCatis
initialized with the results of calling TheFunction(), which is declared on line
25 to return a reference to a SimpleCat.
The body of TheFunction()in lines 35–39 declares a local object of type SimpleCatand
initializes its age and weight. It then returns that local object by reference on line 38.
Some compilers are smart enough to catch this error and don’t let you run the program.
Others let you run the program, with unpredictable results.
When TheFunction()returns, the local object,Frisky, is destroyed (painlessly, I assure
you). The reference returned by this function is 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 9.13 by having TheFunction()
create Friskyon the heap. That way, when you return from TheFunction(),Friskystill
exists.
The problem with this approach is: What do you do with the memory allocated for
Friskywhen you are done with it? Listing 9.14 illustrates this problem.

LISTING9.14 Memory Leaks


1: // Listing 9.14 - Resolving memory leaks
2:
3: #include <iostream>
4:
5: class SimpleCat
6: {
7: public:
8: SimpleCat (int age, int weight);
9: ~SimpleCat() {}
10: int GetAge() { return itsAge; }
11: int GetWeight() { return itsWeight; }
12:
13: private:
14: int itsAge;
15: int itsWeight;
16: };
17:
18: SimpleCat::SimpleCat(int age, int weight)
19: {
20: itsAge = age;
21: itsWeight = weight;
22: }
23:

ANALYSIS
Free download pdf