【发布时间】:2020-04-17 17:26:41
【问题描述】:
您好,我对编写适当的析构函数有点含糊:
class SLLst
{
public:
SLLst() = default;
SLLst(const SLLst&);
SLLst& operator=(SLLst);
~SLLst();
void insert(int);
void remove(int);
private:
SLLst* next = nullptr;
int data = 0;
friend void swap(SLLst&, SLLst&);
friend std::ostream& print(std::ostream&, const SLLst&);
};
SLLst::SLLst(const SLLst& rhs) :
next(rhs.next ? new SLLst() : nullptr),
data(rhs.data)
{
cout << "cpy-ctor" << endl;
}
SLLst& SLLst::operator=(SLLst rhs)
{
cout << "operator=(SLLst)" << endl;
using std::swap;
swap(*this, rhs);
return *this;
}
void swap(SLLst& lhs, SLLst& rhs)
{
cout << "operator=(SLLst)" << endl;
using std::swap;
swap(lhs.next, rhs.next);
swap(lhs.data, rhs.data);
}
SLLst::~SLLst()
{
cout << "dtor" << endl;
delete next;// is this enough?
// or should I use this code?
//SLLst* cur = next;
//SLLst* n = nullptr;
//while (cur != NULL) {
// n = cur->next;
// cur->next = nullptr;
// delete cur;
// cur = n;
//}
}
void SLLst::insert(int x)
{
SLLst* tmp = new SLLst();
tmp->data = x;
if (!next)
{
next = tmp;
return;
}
tmp->next = next;
next = tmp;
}
std::ostream& print(std::ostream& out, const SLLst& lst)
{
auto tmp = lst.next;
while (tmp)
{
out << tmp->data << ", ";
tmp = tmp->next;
}
return out;
}
如您所见,如果我只是在析构函数中使用delete next;,那么我会调用它与列表中的节点一样多,但是为什么许多实现使用循环来释放节点,就像析构函数中的注释代码一样?
因为如果我只在
next上调用delete,那么析构函数将被递归调用,因此我认为我不需要循环来释放析构函数中的节点?对吗?什么时候应该使用循环来释放析构函数中的节点?谢谢!
*如果我运行我的代码,我会得到:
81、77、57、23、16、7、5,
done
dtor
dtor
dtor
dtor
dtor
dtor
dtor
dtor
- 如您所见,dtor 被调用了 8 次;这是否意味着它已正确释放所有节点?
【问题讨论】:
-
@JamesAdkison:但我认为析构函数会被递归调用。
-
我没有查看您的代码,但是在使用循环的实现中,这些类型没有析构函数,对吧?我猜这就是你所做的和那些例子的区别。
-
是的,它应该递归删除所有节点。
-
应谨慎使用递归删除。对于长列表,它可能会导致堆栈溢出。
-
@ChrisMM 这不是答案部分。
标签: c++ linked-list destructor