Avoiding leaks on dynamically created data members
I have the following class, Room, where i'm storing info for each room in the .... you guessed it... RPG world. The program we never end. :)
I've stripped the class code for you of about everything except the part that i'm trying to work out...
Code:
class Room{
private:
char* pDescription; //Note i'm using a pointer here. This is were my question starts
static int tally; //I added this one in the hope it helps solving my problem
public:
~Room(){ delete [] pDescription; tally--; }
Room(const char* desc="Room Description -empty-")
{
if(!(pDescription = new char[strlen(desc)+1]))
{ cout <<"Out of memory!"; exit(1); } //This is my problem. The exit(1) there.
strcpy(pDescription, desc);
tally++;
}
static int Count(){ return tally; }
void Description(){ cout << endl << pDescription; }
};
int Room::tally = 0;
According to what I have there, if the constructor can't allocate memory for the char array, it aborts execution. This is fine and dandy. But if I have other objects of this class in the heap already when this happens, their destructors will never get called, and I will just have this huge memory leak... considering each description data member can be up to 500 characters.
How can I avoid this leak? How should I build that constructor check so that it aborts execution after and only after deallocating all objects created before.
Please note, I need that pDescription there. You could argue I could simply create a [501] array and leave with the wasted space while avoiding having to deal with a dynamically created data member. That is true. But this code belongs to the RPG world builder component and not to the playing one. That is, there's the need of having a supposedly huge array of Room objects open at all times. Hence the need to optimize that particular data member.