如何在Perl中明确销毁对象? [英] How do you explicitly destroy an object in Perl?

查看:62
本文介绍了如何在Perl中明确销毁对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个具有DESTROY方法的Perl类.此方法用于隐式释放外部资源,例如文件句柄或数据库事务.

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.

给出此类的一个实例,我想明确地销毁它.其主要目的是导致调用DESTROY方法,以便可以释放外部资源.但是,将对象"本身从内存中释放会带来更多好处.

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.

我该怎么做?我考虑过直接调用DESTROY方法,并取消定义引用该对象的任何变量.

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

推荐答案

一旦对它们的最后一个引用消失,Perl5对象就会被破坏,除非您具有自引用结构(请参见

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).

如果没有自引用,则无需担心任何事情,DESTROY方法将在需要时被调用;试图自己销毁该对象将是不安全的(如何确定该对象未在其他地方引用),除非您还要对自己进行引用计数(如果这实际上是可能的,那将重复perl的工作,不是一个好主意).

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:

  • 如果要在代码的特定位置释放外部资源,请使用release/close/dispose/任何方法显式地释放外部资源(您的DESTROY代码也可以调用). /li>
  • 如果您不太在意该发布是否恰好在代码中的那个时刻发生,只是最终它确实会被调用,就不必担心.
  • 不用担心perl对象本身.
  • 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.

(换句话说,我不知道一种显式地delete perl对象的方法.这种方法不适用于引用计数的垃圾收集系统.)

(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.)

这篇关于如何在Perl中明确销毁对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆