析构函数在链表中是强制性的吗?

use*_*746 -2 c++ destructor linked-list

我做了一个单链表项目.

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

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();
}
Run Code Online (Sandbox Code Playgroud)

pa1*_*pal 5

默认析构函数只会释放head和tail的内存,因为sll()构造函数只在对象使用时将head和tail初始化为0

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

~sll()
{
    node *p = head;
    while (head !=NULL)
    {
        head= head -> next;
        delete p;
        p=head;
    }
}
Run Code Online (Sandbox Code Playgroud)


kfs*_*one 5

除非您尝试开发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.
}
Run Code Online (Sandbox Code Playgroud)

我们不需要执行"file.close()"或在此进行任何其他清理.它全部封装在我们与istream签订的合同中.当物体消失时,它做了正确的事情.

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

std::string greeting = "Hello, ";
greeting += username;
std::cout << greeting << std::endl;
greeting.freeMemory();
Run Code Online (Sandbox Code Playgroud)

因为string有一个析构函数,所以契约不要求你主动管理它的资源.

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