我制作了一个单链表项目。
我想知道是否需要析构函数或默认析构函数才能正常工作?
class sll
{
node*head;
node*tail;
public:
sll()
{
head=tail=0;
}
sll(const sll & obj1);
void addtohead (int x);
void addtotail (int x);
int deletefromhead();
int deletefromtail();
}
答案 0 :(得分:5)
默认析构函数只会释放head和tail的内存,因为sll()构造函数只在对象intilization时将head和tail初始化为0
它不适用于动态分配的节点。在您的类中实现以下代码。
~sll()
{
node *p = head;
while (head !=NULL)
{
head= head -> next;
delete p;
p=head;
}
}
答案 1 :(得分:5)
除非您尝试开发RAII或良好的代码,否则析构函数不是强制性的。
如果你没有包含析构函数,那么你就会给使用你的类的人带来负担:他们需要知道你没有析构函数,他们必须删除节点在让它们超出范围或摧毁它们之前。
考虑“ifstream”类。
void function(const char* filename) {
if (!haveReadFile) {
ifstream file(filename); // create 'file' and open filename.
if (file.good()) { // file opened.
readFile(file);
haveReadFile = true;
}
}
// .. other stuff.
}
我们不需要执行“file.close()”或在此进行任何其他清理。它全部封装在我们与istream签订的合同中。当物体消失时,它做了正确的事。
与“std :: string”相同 - 你不必做
std::string greeting = "Hello, ";
greeting += username;
std::cout << greeting << std::endl;
greeting.freeMemory();
因为string有析构函数,所以合同不要求你主动管理它的资源。
所以:不要介意析构函数是否是必需的 - 如果没有析构函数,当你的类超出范围时发生的行为是否有意义?会有内存泄漏吗?