析构函数在链表中是必需的

Is Destructor is mandatory in linked lists?

本文关键字:链表 析构函数      更新时间:2023-10-16

我做了一个单链表程序。

我想知道是否需要析构函数或默认析构函数可以正常工作?

class sll
{
    node*head;
    node*tail;
public:
    sll()
    {
        head=tail=0;
    }
    sll(const sll & obj1);
    void addtohead (int x);
    void addtotail (int x);
    int deletefromhead();
    int deletefromtail();
}

默认析构函数只会释放头和尾的内存,因为 sll() 构造函数仅在对象灌输时将头尾初始化为 0

它不适用于动态分配的节点。在类中实现以下代码。

~sll()
{
    node *p = head;
    while (head !=NULL)
    {
        head= head -> next;
        delete p;
        p=head;
    }
}

构函数不是强制性的,除非你正在尝试开发RAII或好的代码。

如果你没有包含析构函数,

那么你就会给使用你的类的人带来负担:他们需要知道你没有析构函数,并且他们必须在让节点超出范围或销毁它们之前删除节点。

考虑"ifstream"类。

void function(const char* filename) {
    if (!haveReadFile) {
        ifstream file(filename); // create 'file' and open filename.
        if (file.good()) {      // file opened.
            readFile(file);
            haveReadFile = true;
        }
    }
    // .. other stuff.
}

我们不需要在这里执行"file.close()"或进行任何其他清理。这一切都被封装在我们与istream的合同中。当物体消失时,它做了正确的事情。

与"std::string"类似 - 您不必这样做

std::string greeting = "Hello, ";
greeting += username;
std::cout << greeting << std::endl;
greeting.freeMemory();

因为 String 有一个析构函数,所以协定不需要你主动管理其资源。

所以:不管析构函数是否是强制性的——如果没有析构函数,当你的类超出范围时发生的行为是否有意义?会不会有内存泄漏?