in reply to Closures, object destruction and memory leaks
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:
showing that the object is destroyed immediately after execute completes.Entering execute Created TestObject Set $SIG{INT} Done with execute DESTROY Execute completed
Update: Fix typo in shebang line.
|
|---|