C++如何触发Class析构函数
C++ How to Trigger Class Destructor
我正在开发一个 class 来处理配置文件,它由许多段组成,每个段有许多 key:value 元素。我有以下代码(简化为基本问题):
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
}
}
};
如果我在主代码中声明一个cfgElement
,它当然会按预期触发析构函数。当 config
对象超出范围时,那些属于 segments[]
数组的部分不会被触发,我能理解为什么不,但是有没有办法获得 cfgElement
析构函数触发那些?我不能 delete
它们,因为它们不是指针。
我可以使 cfgSegment
的 head
元素成为指针,并在 config
构造函数中遍历 segments[]
数组,分配每个 cfgElement
单独,但这是唯一的方法吗?
您只需要删除段而不是删除循环中的每个对象。
~config() {
delete[] segments;
}
我正在开发一个 class 来处理配置文件,它由许多段组成,每个段有许多 key:value 元素。我有以下代码(简化为基本问题):
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
}
}
};
如果我在主代码中声明一个cfgElement
,它当然会按预期触发析构函数。当 config
对象超出范围时,那些属于 segments[]
数组的部分不会被触发,我能理解为什么不,但是有没有办法获得 cfgElement
析构函数触发那些?我不能 delete
它们,因为它们不是指针。
我可以使 cfgSegment
的 head
元素成为指针,并在 config
构造函数中遍历 segments[]
数组,分配每个 cfgElement
单独,但这是唯一的方法吗?
您只需要删除段而不是删除循环中的每个对象。
~config() {
delete[] segments;
}