I am having a hard time deciding whether to use pointers or not in my nested data structures.
Memory and CPU efficiencies are important as I am dealing with data files of sizes on the order of gigabytes.
I have decided to use several classes that are nested in a hiearchical manner to make the code more organized and re-usable.
Here is a simplified version of my code:
struct Segment
{
int start, end, value;
};
class Set
{
private:
vector<Segment*>* segments;
public:
Set() {
segments = new vector<Segment*>();
}
~Set() {
for (size_t i = 0; i < segments->size(); ++i) {
delete segments->at(i);
}
delete segments;
}
vector<Segment*>* getSegments() {
return segments;
}
// accessor functions...
};
class Collection
{
private:
vector<Set*>* sets;
public:
Collection() {
sets = new vector<Set>();
}
~Collection() {
for (size_t i = 0; i < sets->size(); ++i) {
delete sets->at(i);
}
delete sets;
}
void push_back(Set* set) {
sets->push_back(set);
}
// other accessor functions...
};
int main()
{
Collection collection;
// open file, read file
Set* set;
while (!f.eof()) {
Segment* segment = new Segment();
// fill segment
// instantiate set using "new" as needed, and fill it with segments
collection.push_back(set);
}
// do other stuff
return 0;
}
The main motivation to use pointers is so that the child data structures can be built up while reading in the data file, and a pointer is simply passed to the parent data structures, avoiding using accessor functions and copying pieces of data redundantly.
My two main concerns are:
1. Memory leak. Does the order in which the class destructors are called ensure that there is no memory leak? When the collection destructor is called, I needed to "delete sets->at(i)" to deallocate the Set objects allocated elsewhere, but does the Set destructor get called, or does a memory leak result?
2. Kdevelop using gdb does not resolve the pointers, so I cannot see the content of the Collection object during debugging. I have to print them out, which can be cumbersome.
Back in the days when I used to use Visual Studio, I think I was having similar problems when I was using pointers to classes...
Is there a better way to do this?
(Besides using several global vectors to store different data types and hope that I remember to process related data concurrently...)