代码之家  ›  专栏  ›  技术社区  ›  Peter Ajtai

如何在PHP中对此线性链接列表使用unset()。

  •  0
  • Peter Ajtai  · 技术社区  · 14 年前

    我正在用PHP编写一个简单的线性链表实现。这基本上只是为了练习…一部分 Project Euler 问题。我不确定是否应该使用 unset() 帮助垃圾收集以避免内存泄漏。我应该在lll的析构函数中包含head和temp的unset()吗?

    我知道我会在需要的时候使用unset()删除节点,但是unset()在任何时候都是常规清理所必需的吗?

    即使不使用unset(),脚本终止后内存映射是否释放?

    I saw this SO question 但我还是有点不清楚。答案是您不必使用unset()来避免与创建引用相关联的任何类型的内存泄漏吗?

    我用的是php 5……顺便说一句。

    Unsetting references in PHP

    PHP references tutorial

    以下是代码-我在创建$temp和$this时创建引用->在lll类的某些点创建头:

    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/>&nbsp;&nbsp;";
            if ($this->head)
            {               
                $temp =& $this->head;
                do
                {
                    echo $temp->data . " ";
                } while ($temp =& $temp->next);
            } else
            {
                echo "is empty.";
            }
            echo "<br/>";
        }
    }
    

    谢谢!

    1 回复  |  直到 14 年前
        1
  •  2
  •   Amber    14 年前

    一旦脚本 即使不使用也会终止 UNSET()?

    是-脚本结束时, 全部的 它分配的内存资源中有个被释放。