【发布时间】:2011-03-02 22:28:02
【问题描述】:
我正在用 PHP 编写一个简单的线性链表实现。这基本上只是为了练习......Project Euler 问题的一部分。我不确定是否应该使用unset() 来帮助进行垃圾收集以避免内存泄漏。我应该在 LLL 的析构函数中包含 head 和 temp 的 unset() 吗?
我知道我会在需要时使用 unset() 来删除节点,但是 unset() 在任何时候都需要进行常规清理吗?
即使您不使用 unset(),脚本终止后是否会释放内存映射?
I saw this SO question,但我还是有点不清楚。答案是您根本不必使用 unset() 来避免与创建引用相关的任何类型的内存泄漏吗?
我正在使用 PHP 5.. 顺便说一句。
这里是代码 - 当我在 LLL 类中的某些点创建 $temp 和 $this->head 时,我正在创建引用:
class Node
{
public $data;
public $next;
}
class LLL
{
// The first node
private $head;
public function __construct()
{
$this->head = NULL;
}
public function insertFirst($data)
{
if (!$this->head)
{
// Create the head
$this->head = new Node;
$temp =& $this->head;
$temp->data = $data;
$temp->next = NULL;
} else
{
// Add a node, and make it the new head.
$temp = new Node;
$temp->next = $this->head;
$temp->data = $data;
$this->head =& $temp;
}
}
public function showAll()
{
echo "The linear linked list:<br/> ";
if ($this->head)
{
$temp =& $this->head;
do
{
echo $temp->data . " ";
} while ($temp =& $temp->next);
} else
{
echo "is empty.";
}
echo "<br/>";
}
}
谢谢!
【问题讨论】: