Given
package Object {
sub new { my $class = shift; bless({ @_ }, $class) }
}
my $object = Object->new( a => 1, b => 2 );
在第二次作业之前,你有
+============+ +==========+
$object -->[ Reference ---->[ Blessed ]
+============+ [ Hash ]
[ ] +==========+
[ a: --------->[ 1 ]
[ ] +==========+
[ ]
[ ] +==========+
[ b: --------->[ 2 ]
[ ] +==========+
+==========+
(箭头代表指针。)
Perl uses reference counting to determine when to free variables. As part of the assignment, the reference count of the variable currently referenced by the name (the Reference) will be decremented, causing it to be freed[1]. This will drop the reference count of the hash, causing it to be freed[1]. This will drop the reference count of the values, causing them to be freed[1].
在 Perl 中,当有循环引用时,就会出现内存泄漏。
{
my $parent = Node->new();
my $child = Node->new();
$parent->{children} = [ $child ];
$child->{parent} = $parent;
}
在退出区块之前,你必须
$parent +----------------------------------------------------+
| | |
| +============+ +-->+==========+ |
+-->[ Reference -------->[ Blessed ] |
+============+ [ Hash ] |
[ ] +==========+ |
[ children --->[ Array ] |
[ ] [ ] +============+ |
+==========+ [ 0: --------->[ Reference ----+ |
[ ] +============+ | |
+==========+ | |
| |
$child +-------------------------------------------------+ |
| | |
| +============+ +-->+==========+ |
+-->[ Reference -------->[ Blessed ] |
+============+ [ Hash ] |
[ ] +============+ |
[ parent: ---->[ Reference ----------------------+
[ ] +============+
+==========+
存在该块后,您有
+----------------------------------------------------+
| |
+-->+==========+ |
[ Blessed ] |
[ Hash ] |
[ ] +==========+ |
[ children --->[ Array ] |
[ ] [ ] +============+ |
+==========+ [ 0: --------->[ Reference ----+ |
[ ] +============+ | |
+==========+ | |
| |
+-------------------------------------------------+ |
| |
+-->+==========+ |
[ Blessed ] |
[ Hash ] |
[ ] +============+ |
[ parent: ---->[ Reference ----------------------+
[ ] +============+
+==========+
内存没有被释放,因为所有内容仍然被引用,因为存在引用循环。由于您无法访问此结构(没有变量名称引用其中的任何内容),因此这是内存泄漏。
- 假设没有其他东西引用(指向)这些变量。