c++问题析构函数

C++ troubled destructor

本文关键字:析构函数 问题 c++      更新时间:2023-10-16

这是学校的作业,我大部分都在控制之中,但是有一小部分正在创建内存泄漏,我对如何修复它没有更多的想法。

我们创建了一个内存分配器,麻烦的部分是这两个函数。

第一个不能修改

void destroy (){
  free():
  tot_alloc = 0; }

第二个是我正在做的

void free(){
  munmap(pool, PAGE_SIZE);
  Page* f = this;
  f = f->prev;
  if (f != NULL)
    f->destroy();
}

我已经写了所有的free()函数,并在赋值中被要求调用destroy()。我意识到这个函数并没有销毁第一个"this",因为它马上要去f->prev,但我不知道如何让它首先销毁this,然后去prev。

我希望这不是一个太愚蠢的问题。

多谢!

尼科

要从单链表中删除一个元素,必须遍历到该元素以找到它在列表中的前面的元素。然后你得把它"缝"起来。这样的:

void free()
{ // Note: This has no error checking!
    Page *f = tail, *next_f = NULL;
    while(f != this)
    { // find this node to find the node after this node
        next_f = f;
        f = f->prev;
    }
    // found it. Now, next_f is the node after this node.
    // close the chain so this link can go away
    if (next_f == NULL) // there is no node after us, we must be the tail
       tail = prev; // the tail is now whatever node is after us
    else // in the node after us, the node before it is now the node before us
       next_f->prev = prev; 
    destroy(); // we are unlinked from the chain so can now be freed
}