我应该在不会返回到堆栈上的 Perl 的 SV 上调用 SvREFCNT_dec() 吗?

Should I call SvREFCNT_dec() on a SV that is not going to be returned to Perl on the stack?

从 Perl 调用 C 函数时,例如使用 Inline::C:

use feature qw(say);
use strict;
use warnings;
use Inline C => './test.c';

say "Calling test()..";
test();
say "Finished.";

其中 test.c 是:

void test() 
{
    SV *sv_variable = newSVpv("test", 0);

    // do something..

    //SvREFCNT_dec(sv_variable); // free variable
    printf( "Returning from test()..\n");
    return;

}

无论我是否调用 SvREFCNT_dec(sv_variable),脚本似乎都能正常工作。根据 perlguts:

To free an SV that you've created, call SvREFCNT_dec(SV*). Normally this call is not necessary

是的,您应该减少引用计数。 (如果不这样做,不会立即产生不良影响,但会造成内存泄漏。)

perlguts 可能说这通常是不必要的,因为大多数 SV 不仅在 C 函数内部使用;它们是可从 Perl 访问的结构的一部分 space 或放在堆栈上。

但请注意,您的代码结构不是异常安全的:如果 // do something 中的任何函数抛出,sv_variable 将泄漏(因为永远不会到达 SvREFCNT_dec)。这可以通过以下方式解决:

SV *sv_variable = sv_2mortal(newSVpv("test", 0));

sv_2mortal 就像一个延迟的 SvREFCNT_dec:它会在某个时间减少引用计数 "later".

(如果您从字符串文字创建 SV,newSVpvs("test") 优于 newSVpv,因为它不必在运行时计算长度。)