I have a test script like this:
package Test;
sub new { bless {} }
sub DESTROY { print "in DESTROY\n" }
package main;
my $t = new Test;
sleep 10;
The destructor is called after sleep
returns (and before the program terminates). But it's not called if the script is terminated with Ctrl-C. Is it possible to have the destructor called in this case also?
There are two reasons that your destructors aren't being called, one is as kishor8dm pointed out that you are using the operator "new" and because of that the "delete" command must be called explicitly.
A destructor is only an automatic function that activates when the object go out of scope. There is no drawbacks of not using it, if you do not need that function.
The destructor is called after the last statement of the scope containing the variable which is an instance of a class. Save this answer.
No, by default, most signals cause an immediate, abnormal exit of your program. However, you can easily change the default behavior for most signals. If you run this program and press control-C, you should see the word "destructor" printed.
No. You never need to explicitly call a destructor (except with placement new ). A class's destructor (whether or not you explicitly define one) automagically invokes the destructors for member objects. They are destroyed in the reverse order they appear within the declaration for the class.
As Robert mentioned, you need a signal handler.
If all you need is the object destructor call, you can use this:
$SIG{INT} = sub { die "caught SIGINT\n" };
.
You'll have to set up a signal handler.
package Test;
sub new { bless {} }
sub DESTROY { print "in DESTROY\n" }
package main;
my $terminate = 0;
$SIG{INT} = \&sigint;
sub sigint { $terminate = 1; }
my $t = new Test;
while (1) {
last if $terminate;
sleep 10;
}
Something along these lines. Then in your main loop just check $terminate
and if it's set exit the program normally.
What happens is that the cntl-c interrupts the sleep, the signal handler is called setting $terminate
, sleep returns immediately, it loops to the top, tests $terminate
and exits gracefully.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With