C ++删除成员函数中的临时节点?

时间:2015-11-20 19:58:36

标签: c++ pointers linked-list set

我正在实现一个类Set,并且有成员函数,具有讽刺意味的是member,如果传递的值在set中,则返回true,否则返回false。我的问题是,如果我创建一个临时节点来迭代搜索这个值,我是否需要删除这个临时节点,当我完成它以将内存返回到堆时,因为它不是从功能?

在这个类中,节点作为私有结构嵌入到类Set中:

private:
  //Precondition: linked list is sorted in ascending order
  struct Node {
     int value;
     Node* link;
  };
  Node* list;
  static Node* cons(int x, Node *p);

我所指的功能是:

bool Set::member(int x) const {
   if(list == nullptr) 
      return false;

   Node* tempNode = list;

   while(tempNode != nullptr) {
      if(tempNode->value > x) 
         return false;
      if(tempNode->value == x) 
         return true;
      tempNode = tempNode->link;
   }
   return false;
}

2 个答案:

答案 0 :(得分:1)

tempNode只是一个automatic storage duration的非静态局部变量;它的范围仅限于函数的开头和结尾。当函数返回时,自动解除分配

答案 1 :(得分:0)

您的member函数未分配任何堆内存(没有newmalloc调用)。 tempNode变量(大小为sizeof(Node*))将在堆栈上分配。

当函数退出时,整个函数(包含tempNode)的激活记录会自动解除分配,因此无需进一步清理。

代码是正确的。