Oleksiy
Oleksiy

Reputation: 39800

Is it safe to delete a linked list in its own destructor?

I want to clean up any resources I acquired earlier, so in my destructor I call the function clear that deletes the whole linked list:

LinkedList::~LinkedList() {
    clear();
}

Is it safe to do that? Is there a chance of an exception? This is what clear looks like:

// 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;

}

Upvotes: 0

Views: 99

Answers (1)

Aleksei Petrenko
Aleksei Petrenko

Reputation: 7168

I think this is what you usually do in LL destructors. Your LinkedList class is just a wrapper around the chain of Nodes, so it is safe as long as you check for null pointers in other LinkedList methods.

Also if this is not your computer science home task, consider using std::list :)

Upvotes: 1

Related Questions