我需要确认使用newHV创建的HV是否需要释放?

8
如果我写了一些包含哈希的XS代码,我不希望将其返回给perl,那么我需要释放它吗?如果需要,该怎么做?
我想到的最接近的方法是hv_undef,但据我所知,这仅清除哈希的内容,而不是哈希本身。
HV* hash = newHV();
...
use the hash
...
hv_undef(hash);
2个回答

10

newHV(类似于newSVnewAV等)将新创建的值的引用计数设置为1。要释放它,只需要将其减少到0。对于 HV,没有专门的函数,因此只需使用SvREFCNT_dec

HV* hash = newHV();
/*
 * use the hash
 */
SvREFCNT_dec((SV *) hash);

太好了。我想在我的脑海中,HV作为SV的子类部分并没有起作用。这个很棒。 - Eugene Marcotte

7

newHV返回一个HV,其引用计数(refcnt)为1,表示您的代码对该HV的持有。当您使用完该HV时,必须通过减少其refcnt来释放您对其的持有。这可以通过以下三种常见方法之一来实现。

  1. Done with it here and now.

    SvREFCNT_dec((SV*)hv);
    // hv is no longer safe to use here.
    

    AV and HV are "subclasses" of SV.

  2. Done with it after the caller has a chance to reference it. (Doesn't really apply to hashes.)

    return sv_2mortal(sv);
    
  3. Transfer "ownership".

    rv = newRV_noinc((SV*)hv);
    

    That's short for

    rv = newRV((SV*)hv);
    SvREFCNT_dec((SV*)hv);
    

    Note that you must similarly release your hold on the rv when you're done with it, so you'll often see the following:

    return sv_2mortal(newRV_noinc((SV*)hv));
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接