perl的过载并置运算符(“”)问题

问题描述 投票:7回答:1

请帮我明白了,为什么引用计数为每个级联的增长?我在过载子返回相同的对象,并期望,即引用计数将保持不变。但是,看来,Perl的克隆和存储对象的地方每次。为什么和我如何避免这种情况?

此外,我期待,该对象将在退出作用域之后摧毁,但由于非零引用计数销毁了只在全球毁灭的阶段。这看起来像一个内存泄漏。

#!/usr/bin/env perl

use strict;
use warnings;
use Devel::Refcount qw[refcount];

package AAA {
    use Devel::Refcount qw[refcount];

    use overload
      '.' => sub {
        print 'CONCAT, REFCOUNT: ', refcount( $_[0] ), "\n";

        # return AAA->new;
        return $_[0];
      },
      fallback => 0;

    sub new { return bless {}, $_[0] }

    sub DESTROY { print "DESTROY\n" }
}

print "--- start\n";

{
    my $o = AAA->new;

    my $s = '1' . ( '2' . ( '3' . ( '4' . ( '5' . $o ) ) ) );

    print "--- exit scope\n";
    print 'REFCOUNT: ', refcount($o), "\n";
}

print "--- end\n";

1;

下测试

  • Perl的5.28.1 64
  • 杰韦利::引用计数0.10
  • 超载1.30

产量

--- start
CONCAT, REFCOUNT: 1
CONCAT, REFCOUNT: 3
CONCAT, REFCOUNT: 5
CONCAT, REFCOUNT: 7
CONCAT, REFCOUNT: 9
--- exit scope
REFCOUNT: 6
--- end
DESTROY
perl
1个回答
7
投票

就像延迟DESTROY信息,添加弱裁判的对象指示的泄漏。泄漏似乎已经在Perl 5.28中引入。

use strict;
use warnings;
use Scalar::Util qw( weaken );

package AAA {
    use overload
        '.' => sub { $_[0] },
        fallback => 0;

    sub new { return bless {}, $_[0] }

    sub DESTROY { print "DESTROY\n" }
}

my $w;
{
    my $o = AAA->new;
    weaken($w = $o);
    my $s = '1' . ( '2' . ( '3' . ( '4' . ( '5' . $o ) ) ) );
    print "Exiting scope...\n";
}

print "leak!\n" if defined($w);
#use Devel::Peek;
#Dump($w);

print "Global destruction...\n";

输出(前5.28):

Exiting scope...
DESTROY
Global destruction...

输出(5.28.0和5.28.1):

Exiting scope...
leak!
Global destruction...
DESTROY

请报告使用perlbug命令行实用程序。 错误报告可以发现here。 它已被固定在5.30。这可能是固定在5.28.2。

© www.soinside.com 2019 - 2024. All rights reserved.