如何从链接列表上的节点释放已分配类的内存

时间:2016-06-08 20:05:31

标签: c++ oop memory-management linked-list

在我的代码中,我创建了一个节点列表,这些节点带有指向动态分配的类对象的指针,我似乎无法弄清楚如何确保在删除特定节点时释放内存。

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

当我删除节点时,类对象中的析构函数会为我处理吗?或者在我的节点删除功能中,我应该包含以下内容:

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

这是我的节点结构:

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

1 个答案:

答案 0 :(得分:2)

您需要明确delete使用new分配的任何内容(除非您使用智能指针包装器,如std::unique_ptrstd::shared_ptr)。您需要delete node,并且需要delete Dog

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

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

如果node意图拥有Dog对象,那么您可以向node添加析构函数以执行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'...

或者,您根本不能使用new来分配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...

然后当你想到这一切时,摆脱你的手动链表实现并改用std::list,让它为你管理节点:

#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);