【发布时间】:2014-07-31 19:16:25
【问题描述】:
我正在尝试按对象删除分配的内存,但它是以链表的形式。有人可以建议一种方法吗?
这是我的头文件
class XKey
{
public:
XKey();
virtual ~XKey();
private:
char *m_name;
char *m_value;
XKey *m_next;
};
class XSection
{
public:
XSection();
virtual ~XSection();
private:
char *m_name;
XKey *m_keys;
XSection *m_next;
};
class XIniFile
{
public:
XIniFile();
virtual ~XIniFile();
private:
char *m_name;
XSection *m_sections;
};
这是我的程序文件
XKey::~XKey()
{
delete(m_name);
delete(m_value);
m_next = 0;
}
XSection::~XSection()
{
XKey k;
XKey ks;
k = m_keys;
while (k){
ks = k;
k = k->getNext();
//////////////<<<--- How can I call a destructor here from XKey?
delete(m_name);
m_keys = 0;
m_next = 0;
}
}
XIniFile::~XIniFile()
{
XSection *sec;
XSection *sp;
sec = m_sections;
while (sec) {
sp = sec;
//////////////<<<--- How can I call a destructor here from XSection?
delete(m_name);
m_sections = 0;
}
}
我有一些错别字,但请关注我如何在析构函数中调用析构函数的算法。谢谢!
【问题讨论】:
-
您使用
delete调用析构函数,如delete k或delete s。 -
“调用析构函数”是什么意思?您不会手动调用析构函数(除非您使用的是placement new,但那是另一回事)。当对象为
delete'd 时会自动调用它们。此外,delete(sp->getName());很糟糕,表明您的数据结构缺乏封装和单一职责。 -
@BryanChen 不要使用指针。这里完全没有必要。
-
恕我直言,以上所有 cmets 应形成一个社区答案 :)
-
@KonradRudolph 你的意思是不要使用 raw 指针?没有指针就无法实现链表。
标签: c++ destructor