【发布时间】:2013-12-25 03:39:01
【问题描述】:
我想清理之前获得的所有资源,所以在我的析构函数中调用函数clear 删除整个链表:
LinkedList::~LinkedList() {
clear();
}
这样做安全吗?有例外的机会吗?这就是clear 的样子:
// deletes all nodes in a linked list
void LinkedList::clear() {
Node* current = head;
while (current) {
Node* next = current->next;
delete current;
current = next;
}
head = nullptr;
}
【问题讨论】:
-
是的,IMO 很好,如果您不想要求用户在销毁之前手动
clear(),您应该这样做(而且您绝对不会这样做)想要那个)。 -
对我来说看起来不错。只要你不在析构函数中做类似
delete this;的事情:)
标签: c++ exception linked-list destructor