简体   繁体   中英

How do I deallocate memory for allocated class from node on Linked List

In my code I've made a list of nodes who carry pointers to dynamically allocated class objects and I can't seem to figure out how to make sure I free the memory upon deletion of a specific node.

//create temporary node
node *temp = new node;
//create the pointer to the class
Dog *thisDog = new Dog(age, name);
//set the next pointer to NULL (points to nothing)
temp->next = NULL;
//set first value in list to temp
head = temp;
//set last value to temp
last = temp;

Will the destructor within the class object take care of this for me when I delete the node? Or within my node deletion function should I include something such as the following:

//delete one element
delete *&thisDog;
delete head;
//set the head and last pointer to NULL, point to nothing
head = NULL;
last = NULL;

Here is my node structure:

struct node
{
    Dog *thisDog;
    node *next;
};

You need to explicitly delete anything you allocate with new (unless you use a smart pointer wrapper, like std::unique_ptr or std::shared_ptr ). You need to delete the node , and you need to delete the Dog :

node *temp = new node;
...
delete temp;

Dog *thisDog = new Dog(age, name);
...
delete thisDog;

If node is meant to own the Dog object, then you can add a destructor to node to perform that delete :

struct node
{
    Dog *thisDog;
    node *next;

    node() : thisDog(NULL), next(NULL) {}
    ~node() { delete thisDog; }
};

node *temp = new node;
node->thisDog = new Dog(age, name);

...

delete node; // calls 'delete thisDog'...

Or, you could simply not use new at all to allocate the Dog :

struct node
{
    Dog thisDog;
    node *next;

    node(int age, string name) : thisDog(age, name), next(NULL) {}
};

node *temp = new node(age, name);

...

delete node; // frees 'thisDog' automatically...

And then when you have that all figured out, get rid of your manual linked-list implementation and use std::list instead, let it manage the nodes for you:

#include <list>

std::list<Dog> mylist;

Dog thisDog(age, name);
mylist.push_back(thisDog);

Dog thisDog(age, name);
mylist.push_front(thisDog);

mylist.pop_back();

mylist.pop_front();

std::list<Dog>::iterator iter = ...; // any method that returns an iterator to a list element
mylist.erase(iter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM