我试图通过对象删除已分配的内存,但它是以链表的形式。有人可以建议吗?
这是我的头文件
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;
}
}
我有一些拼写错误,但请关注算法如何在析构函数中调用析构函数。谢谢!
答案 0 :(得分:4)
如果您将RAII与std::string
,std::list
和std::unique_ptr
一起使用,
你不必在析构函数中手动执行某些操作:
#include <list>
#include <string>
#include <memory> // unique_ptr
class XKey
{
public:
virtual ~XKey() = default;
private:
std::string m_name;
std::string m_value;
};
class XSection
{
public:
virtual ~XSection() = default;
private:
std::string m_name;
std::list<std::unique_ptr<XKey>> m_keys;
};
class XIniFile
{
public:
virtual ~XIniFile() = default;
private:
std::string m_name;
std::list<std::unique_ptr<XSection>> m_sections;
};
如果这些课程不需要是多态的,您可以使用std::list<T>
代替std::list<std::unique_ptr<T>>
。
答案 1 :(得分:1)
XSection::~XSection()
{
XKey* k = m_keys; // must be a pointer!
while (k){
XKey* ks = k; // must be a pointer!
k = k->getNext();
if (ks != nullptr) delete ks;
}
delete [] m_name; // allocated with new[]?
}
这是非常c ++ 98,您应该考虑使用c ++ 11(智能指针)