I'm worried that by using a closure like this $req will never get destroyed due to dangling references.
Unless there's something you're not telling us, you should be okay. The operative line is here:
local $SIG{INT} = sub { $req->handleInterrupt };By scoping $SIG{INT} dynamically, you ensure that it will pass out of scope at the end of the block. At that time, the coderef it stored will be thrown away, and assuming that's the only reference to the anonymous sub in question, the anonymous sub's reference count should drop to zero, and it will be harvested; consequently, it will drop its reference to $req->handleInterrupt so that that also can be cleaned up, unless something somewhere else is holding another reference.
Generally speaking, you need to be careful about memory leaks with closures under the same circumstances as with any other references -- primarily when you have circular constructs, e.g., like the following:
sub createcircle { my ($foo, $bar) = @_; my $qux; my $quux = sub { if (shift==$foo) { $bar } else { $qux->() } }; $qux = sub { $quux->(shift - 1) }; return $quux; }
$;=sub{$/};@;=map{my($a,$b)=($_,$;);$;=sub{$a.$b->()}} split//,".rekcah lreP rehtona tsuJ";$\=$ ;->();print$/
In reply to Re: Closures, object destruction and memory leaks
by jonadab
in thread Closures, object destruction and memory leaks
by mpeppler
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |