C++ 如何从链表上的节点取消分配已分配类的内存
在我的代码中,我列出了一个节点列表,这些节点携带指向动态分配的类对象的指针,但我似乎不知道如何确保在删除特定节点时释放内存C++ 如何从链表上的节点取消分配已分配类的内存,c++,oop,memory-management,linked-list,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;
//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;
};
您需要显式地
删除使用新建分配的任何内容(除非您使用智能指针包装,如std::unique\u ptr
或std::shared\u ptr
)。您需要删除节点
,并且需要删除狗
:
node *temp = new node;
...
delete temp;
struct node
{
Dog thisDog;
node *next;
node(int age, string name) : thisDog(age, name), next(NULL) {}
};
如果节点
打算拥有狗
对象,则可以向节点
添加析构函数以执行该删除
:
struct node
{
Dog *thisDog;
node *next;
node() : thisDog(NULL), next(NULL) {}
~node() { delete thisDog; }
};
或者,您根本不能使用new
来分配狗
:
node *temp = new node;
...
delete temp;
struct node
{
Dog thisDog;
node *next;
node(int age, string name) : thisDog(age, name), next(NULL) {}
};
然后,当您解决了所有这些问题后,请放弃手动链表实现,改用,让它为您管理节点:
#include <list>
std::list<Dog> mylist;
std::list::iterator iter=…;//向列表元素返回迭代器的任何方法
mylist.erase(iter);
删除*&thisDog代码>-这本身就应该是一个迹象,表明某些事情可能发生了冲突,因为删除这只狗代码>应该足够了。您是否打算将thisDog
放在列表中的某个位置,因为您发布的代码中没有出现这种情况。请用相关内容更新您的问题。非常感谢,这正是我要找的。我最初试图不分配任何东西,但这个程序更多的是一个内存分配的实践,内存泄漏。
#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);