The actual code is the sub once of Mojo::EventEmitter
The author must have done this for some reason...
Yeah, well Mr. Sherlock, that code is different than what you posted. The reason is always the same, circular references prevent release of memory
{
my $foo = {}; # ref count 1
$foo->{foo} = $foo; # ref count 2
} ### $foo goes out of scope here, memory should be released to perl
# here, $foo is not addressable (you can't refer to it by $foo),
# but its memory is not released until exit
# because there is still a reference to $foo
# it refers to it self, its self-referential, a circular reference
# for memory held by $foo to be released after $foo goes out of scope
# $foo->{foo} has to be weakened, the reference count decreased
The actual code, which you should have copy/pasted to get a reasonable answer, since editing code you don't understand changes its meaning
sub once {
my ($self, $name, $cb) = @_;
weaken $self;
my $wrapper;
$wrapper = sub {
# a special kind of circular reference
# CLOSURE, $wrapper keeps $self alive after return $wrapper (REFCNT+1)
# $wrapper refers to itself, CIRCULAR REFERENCE
$self->unsubscribe($name => $wrapper);
$cb->(@_);
};
$self->on($name => $wrapper); # potential CIRCULAR REFERENCE (on pro
+bably also stores $wrapper, but it probably also uses weaken )
weaken $wrapper;
return $wrapper;
}
How do I post a question effectively? says, when reducing code size, reduce to the essence, don't change the essence :) |