简体   繁体   English

链表节点的析构函数

[英]Destructor for a linked-list node

I have a Node class and a List class in my linked list.我的List有一个Node类和一个List类。 Do I need a destructor inside my Node class, or should I just use the destructor in my List class to delete all of the nodes?我的Node类中是否需要析构函数,还是应该只使用List类中的析构函数来删除所有节点?

Here's my .h so far:到目前为止,这是我的 .h:

class Node
{

public:

    int value;
    Node* next;
    Node();
    Node(int);
};

class List
{

private:

     Node* head;

public:

    List();
    List(List &a);
    ~List();
    //additional functions (insert, delete, etc)
};

It really depends how you create your linked list node.这实际上取决于您如何创建链表节点。 If you "new" it, then you have to call "delete" in order to free the memory.如果您“新建”它,那么您必须调用“删除”以释放内存。 From your class definition it looks like you are not allocating anything in your constructor.从您的类定义来看,您似乎没有在构造函数中分配任何内容。 If, in your constructor you allocate any memory, then you HAVE to deallocate it in your destructor.如果在构造函数中分配了任何内存,则必须在析构函数中释放它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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