Dynamic memory for Objects

For a program that I am writing to analyze soccer data, I have a constructor for a class that takes a filename and constructs the class from everything in that text file.

This class is called WC, for "world cup," because each text file corresponds to the data for one world cup. Each line the text file corresponds to the data for one Game. Games are also a class. You can see where I'm going with this -- because there's no way for the constructor to know initially how many games are going to be in a text file, I have to dynamically allocate memory for every game. I do this like so...

1
2
3
4
5
6
7
8
9
10

Game * curgame;
//find out how many games are int he text file, store this info as Gnum

curgame = new Game[Gnum];

//later we read the data from each line into a bunch of variables
// that correspond to our class game, and make the call... 

curgame[gamenumber] = Game(...data and stuff...); 


This code works, but it worries me. After the WC is created, what happens to this array of games that I've created? Where is it in memory? i don't know anything about using "new" inside a constructor but it doesn't seem like a very good idea. Later I should use delete[] to free the memory, no? WC stores a vector of pointers to these games. Should I just have the destructor for WC iterate through this vector to delete these games when I'm done?


My other question is, is there another way to do this? The way I have things set up its more convenient to have an array of pointers to games, not actual games. What I'm doing now is just creating an array of pointers to games (call it gpointers), then having each member of gpointers point to a Game in the array of Games I've created. This seems kind of redundant.

Anyways, any help for other ways to think about this would be appreciated!

Cheers,

-Trent
Where is it in memory?
On the heap.

i don't know anything about using "new" inside a constructor but it doesn't seem like a very good idea.
Relax. Many things can't be done at all without using new in a constructor.

Should I just have the destructor for WC iterate through this vector to delete these games when I'm done?
delete[] already does this. The runtime knows how long arrays allocated by new[] are.

is there another way to do this?
Yes, many. Here's one that's not too different but better in some ways:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//Creates the array and calls default constructors:
std::vector<Game> curgame(Gnum);
for (/*...*/)
    curgame[gamenumber] = Game(/*...*/); 
//Nothing needs to be explicitly cleaned up.

//Alternatively:

std::vector<Game> curgame;
//Creates the array without calling constructors:
curgame.reserve(Gnum);
for (/*...*/)
    curgame.push_back(Game(/*...*/));
//Still nothing needs to be explicitly cleaned up. 
Is it cheap to copy a Game? I'd stay away from arrays of pointers if I can.
Last edited on
Topic archived. No new replies allowed.