Reputation: 470
I'm developing a class to process config files, which consist of a number of segments, each segment with a number of key:value elements. I have the following code (pared down to just the basic issue):
class cfgElement {
public:
char *key;
char *val;
cfgElement *link;
cfgElement() {
key = nullptr;
val = nullptr;
link = nullptr;
}
~cfgElement() {
if (key != nullptr) delete key;
if (val != nullptr) delete val;
key = nullptr;
val = nullptr;
link = nullptr;
}
};
struct cfgSegment {
char Name[16];
cfgElement head;
};
class config {
private:
cfgSegment *segments;
public:
config() {
segments = new cfgSegment[5];
}
~config() {
for (int i=0; i<5; i++) {
// Clean up segments[i].head
}
}
};
If I declare a cfgElement
in the main code, it of course triggers the destructor as expected. Those which are part of the segments[]
array do not get triggered when the config
object goes out of scope, and I can understand why not, but is there a way to get the cfgElement
destructor to trigger for those? I can't delete
them, as they are not pointers.
I could make the head
element of cfgSegment
a pointer, and loop over the segments[]
array in the config
constructor, allocating each cfgElement
individually, but is that the only way to do it?
Upvotes: 1
Views: 707
Reputation: 862
You need just to delete segments instead of deleting each object in the loop.
~config() {
delete[] segments;
}
Upvotes: 1