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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.