How do you explicitly destroy an object in Perl?

2020-03-09 11:17发布

Let's say I have a Perl class that has a DESTROY method. This method is used to implicitly release an external resource, such as a file handle or database transaction.

Given an instance of this class, I would like to explicitly destroy it. The primary purpose of this is to cause the DESTROY method to be called so the external resource can be released. However, having the "object" itself released from memory would be an added benefit.

How can I do this? I have considered directly calling the DESTROY method and undefining any variables that reference the object.

标签: perl oop
2条回答
叼着烟拽天下
2楼-- · 2020-03-09 11:30

Perl5 objects get destructed as soon as the last reference to them disappears, unless you have self-referential structures (see Destructors and the Two phase garbage collection paragraph after that for some interesting information).

If you don't have self-references, you don't need to worry about anything, the DESTROY method will be called when it needs to be; trying to destruct the object yourself would not be safe (how can you be sure the object isn't references somewhere else), unless you're also doing reference counting yourself (if that's actually possible, and that would be duplicating perl's efforts, which isn't such a good idea).

So I'd say, as long as you don't have cyclic references:

  • If you want to release external resources at a specific point in your code, do so explicitly with a release/close/dispose/whatever method (that your DESTROY code could call too).
  • If you don't really care that that release happens exactly at that point in your code, just that it does get called eventually, don't worry about it.
  • Don't worry about the perl object itself.

If you do have cyclic references, you'll need to be much more careful, and use weak references (see Scalar::Util) to break the cycles.

(In other words, I don't know of a way to explicitly delete a perl object. That doesn't work well with a reference-counted garbage collection system.)

查看更多
甜甜的少女心
3楼-- · 2020-03-09 11:38

You can use undef to explicitly destroy an object. The below code illustrates it.

package MyPackage;

sub new {
    print "In new\n";
    return bless {};
}

sub DESTROY {
    print "In DESTROY\n";
}

package main;

my $Obj = MyPackage->new();
<STDIN>;
undef $Obj;
<STDIN>;
查看更多
登录 后发表回答