Previous Section  < Free Open Study >  Next Section

Returning a Memory Leaking Dynamically Allocated Object


#include <iostream.h> 

class Point {

 int x, y;

 char* color;

public:

 Point(int = 0, int = 0, char* = ''Red'');

 ~Point();

 Point(const Point&);

 void print();

 const Point& operator=(const Point&);

 const Point& operator+(const Point&);

};

const Point&

Point::operator+(const Point& rhs)

{

 Point *temp = new Point;

 temp->x = x + rhs.x;

 temp->y = y + rhs.y;



// This deletion is necessary due to the nature

// of calling the constructor for Point with

// zero arguments.

 delete temp->color;



// Not exactly a good color-mixing scheme!

temp->color = new char[strlen(color)+

        strlen(rhs.color)+1];

sprintf(temp->color, ''%s%s'', color, rhs.color);

 return(*temp);

}

The C++ developer writing this software tests it extensively (complete with nested calls) and finds that it works flawlessly. It is shipped to numerous clients, some of whom begin complaining of memory leakage problems. Where is this memory leakage? This problem is best illustrated by posing the question, "Where is the temp object, which is dynamically allocated upon each invocation of Point::operator+, cleaned up?" Its destructor is not called automatically since pointers never invoke an object's destructor implicitly. The caller cannot explicitly call the Point object's destructor since the address of the object is not available. Consider the C++ code z = x + y;. How does a user retrieve the address of the temp object?

The answer, of course, is that he or she cannot retrieve the address and, therefore, cannot destroy the temp object. The temp object created upon each invocation of Point::operator+ is leaked from the application and cannot be retrieved.

Our initial premise, that we need to return a reference to a Point object from Point::operator+, was an error. As it turns out, nonmodifying operators must always return an object and not a reference to an object. The object returned is of the automatic storage class.

    Previous Section  < Free Open Study >  Next Section