I believe that what you have there will destroy $req when the execute sub exits. At that time, $req will go out of lexical scope, and the local $SIG{INT} will also go out of scope, so there will be no leftover references to $req and it will go away.

If you hadn't made $SIG{INT} local, $req would stay in scope until it was set to something else.

Here's a test program I wrote to confirm this.

#!/usr/bin/perl -w use strict; package TestObject; sub new { my $class = shift; my $self = {}; bless $self,$class; } sub somesub { my $self = shift; print "Called somesub\n"; } sub DESTROY { my $self = shift; print "DESTROY\n"; } package main; print "Entering execute\n"; &execute; print "Execute completed\n"; sub execute { my $req = TestObject->new or die "Couldn't create TestObject\n"; print "Created TestObject\n"; local $SIG{INT} = sub { $req->somesub }; print "Set \$SIG{INT}\n"; sleep(1); print "Done with execute\n"; }

It produces:

Entering execute Created TestObject Set $SIG{INT} Done with execute DESTROY Execute completed
showing that the object is destroyed immediately after execute completes.

Update: Fix typo in shebang line.


In reply to Re: Closures, object destruction and memory leaks by sgifford
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.