1: // Listing 9.14
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() { 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: itsAge(age), itsWeight(weight) {}
20:
21: SimpleCat & TheFunction();
22:
23: int main()
24: {
25: SimpleCat & rCat = TheFunction();
26: int age = rCat.GetAge();
27: cout << "rCat is " << age << " years old!\n";
28: cout << "&rCat: " << &rCat << endl;
29: // How do you get rid of that memory?
30: SimpleCat * pCat = &rCat;
31: delete pCat;
32: // Uh oh, rCat now refers to ??
33: return 0;
34: }
35:
36: SimpleCat &TheFunction()
37: {
38: SimpleCat * pFrisky = new SimpleCat(5,9);
39: cout << "pFrisky: " << pFrisky << endl;
40: return *pFrisky;
41: }
Output: pFrisky: 0x2bf4
rCat is 5 years old!
&rCat: 0x2bf4
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.
Moze li mi neko od specijalista ispisati to 3. i pravo resenje ?
Hvala