【问题标题】:Is it safe to delete a linked list in its own destructor?在自己的析构函数中删除链表是否安全?
【发布时间】: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


【解决方案1】:

我认为这是你通常在 LL 析构函数中所做的。您的 LinkedList 类只是节点链的包装器,因此只要您在其他 LinkedList 方法中检查空指针,它就是安全的。

另外,如果这不是您的计算机科学家庭任务,请考虑使用 std::list :)

【讨论】:

    猜你喜欢
    • 2015-05-31
    • 1970-01-01
    • 2019-09-20
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 2020-04-17
    相关资源
    最近更新 更多