聘我网

新概念招聘3.0

匿名数组/哈希的生命周期

vote up0vote downstar
@a = ({1,2,3}, [1,2,3]);

这里当@a被回收时,{1,2,3}[1,2,3]会被回收么,如何证明?

 

1 个答复

vote up0vote downcheck
  1. @a被回收时,valuesrefcount都会减1
  2. 当匿名数组/哈希的refcount0时,将被回收,同时递归进行步骤1

所以:

@a = ({1,2,3}, [1,2,3]);

@a被回收时,{1,2,3}[1,2,3]refcount都将变为0,从而将被回收。

可以通过对象的destructor来验证这一点:

perl -e'
   {
       package X ;
          sub new { my ($c,$n) = @_; bless(\$n, $c) }
          DESTROY { print ${$_[0]},"\n"; }

       {
          my @a = (
         { a => X->new(1), b => X->new(2) },
         [ X->new(3), X->new(4) ],
          );
          print "Before end of scope\n";
       }
       print "After end of scope\n";
   }
'

输出是:

Before end of scope
4
3
2
1
After end of scope

要特别注意的是对于%hash只会对其values进行refcount1(当把引用用作key时,会被转为字符串,同时立马refcount1):

perl -e'
   {
       package X ;
          sub new { my ($c,$n) = @_; bless(\$n, $c) }
          DESTROY { print ${$_[0]},"\n"; }

       {
          my @a = (
         { X->new(1), X->new(2) },
         [ X->new(3), X->new(4) ],
          );
          print "Before end of scope\n";
       }
       print "After end of scope\n";
   }
'

输出:

1
Before end of scope
4
3
2
After end of scope
链接

您的回答





不是您要找的问题? 浏览其他含有标签 的问题或者 自己问个.