3

I ran into this piece of code in a (fairly well respected) book. (Note: "head" is a pointer of type Element)

Stack::~Stack(){
  while(head){
    Element *next = head->next;
    delete head;
    head = next;
   }
    return;
}

From my understanding, the delete keyword de-allocates the memory assigned to a pointer. How is it that the author has used the pointer in the next line, immediately after de-allocating it? This confused me a bit. Am I missing something really obvious?

4

2 回答 2

10

作者如何在取消分配后立即在下一行使用指针?

作者正在重新分配指向下一个元素的指针。

delete正在释放 head 指向的内存。它不会“释放”指针本身 - 指针仍然存在并且可以使用。

head = next然后head指向不同的内存块(由 指向的块next)。被删除的内存不再使用,所以没有问题。

于 2013-07-12T21:06:39.223 回答
1

好问题。打个比方:老板昨天解雇了鲍勃;怎么,今天鲍勃的办公桌上有人?

令人困惑的是,通过类比,C++ 语法并没有delete Bob;,而是delete Bobs_desk;——这实际上意味着删除 Bob 办公桌上的员工,但并没有摆脱办公桌。

鲍勃离开后,老板仍然可以让其他人坐在鲍勃的办公桌旁。你跟吗?

于 2013-07-12T21:11:45.353 回答