Memory Leak Problem

Is the memory leak in the below code because the function MakeCat creates a pointer to a Cat object and never deletes the Cat object? If so, how can I should I address the problem?

Thanks!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

class CAT
{
 public:
  CAT(int age){ itsAge = age; }
  ~CAT(){}
  int GetAge() const { return itsAge;}
 private:
  int  itsAge;
};

CAT & MakeCat(int age);
int main()
{
 int age = 7;
 CAT Boots = MakeCat(age);
 cout << "Boots is " << Boots.GetAge()
      << " years old" << endl;
return 0;
}

CAT & MakeCat(int age)
{
 CAT * pCat = new CAT(age);
 return *pCat;
}
Just return the object:
1
2
3
4
CAT MakeCat(int age)
{
  return CAT(age);
}
Thank you, Cubbi.
Note that, for Cubbi's solution to work, CAT must either have a copy constructor or be safely shallow-copiable. Cubbi's solution creates a temporary, unnamed CAT object, and then copies it back to the calling code (i.e. into Boots). Depending on the compiler optimisation, it might make more temporary copies too.

So if CAT can't be safely copied, then this solution won't work properly.

In this case, CAT can be safely shallow-copied, so it will work, but for other data types, it might not be.

If you want to dynamically allocate the CAT object and pass back a pointer, then you need to make sure that, at an appropriate point, you delete it.
Cubbi's solution creates a temporary, unnamed CAT object, and then copies it back to the calling code (i.e. into Boots). Depending on the compiler optimisation, it might make more temporary copies too.

If the compiler would create just one temporary copy in that case, I would throw it out at once.
Topic archived. No new replies allowed.