⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch13_03.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
字号:
<HTML><HEAD><TITLE>Recipe 13.2. Destroying an Object (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen &amp; Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly &amp; Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:42:16Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="ch13_01.htm"TITLE="13. Classes, Objects, and Ties"><LINKREL="prev"HREF="ch13_02.htm"TITLE="13.1. Constructing an Object"><LINKREL="next"HREF="ch13_04.htm"TITLE="13.3. Managing Instance Data"></HEAD><BODYBGCOLOR="#FFFFFF"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch13_02.htm"TITLE="13.1. Constructing an Object"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 13.1. Constructing an Object"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch13_01.htm"TITLE="13. Classes, Objects, and Ties"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch13_04.htm"TITLE="13.3. Managing Instance Data"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 13.3. Managing Instance Data"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch13-39047">13.2. Destroying an Object</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch13-pgfId-413">Problem<ACLASS="indexterm"NAME="ch13-idx-1000004484-0"></A><ACLASS="indexterm"NAME="ch13-idx-1000004484-1"></A></A></H3><PCLASS="para">You want to run special code whenever an object is no longer used. This is sometimes needed when the object is an interface to the outside world  &nbsp;-   or contains circular data structures  &nbsp;-   and must clean up after itself. You might remove temporary files, break circular links, gracefully disconnect from a socket, or kill a spawned subprocess.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch13-pgfId-419">Solution</A></H3><PCLASS="para">Create a method named <CODECLASS="literal">DESTROY</CODE>. This will be called when there are no more references to the object, or else when the program shuts down, whichever comes first. You don't need to do any memory deallocation here, just any finalization code if it makes sense for the class.</P><PRECLASS="programlisting">sub DESTROY {    my $self = shift;    printf(&quot;$self dying at %s\n&quot;, scalar localtime);} </PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch13-pgfId-433">Discussion</A></H3><PCLASS="para">Every story has a beginning and an end. The beginning of the object's story is its constructor, explicitly called when the object comes into existence. The end of its story is the <EMCLASS="emphasis">destructor</EM>, a method implicitly called when an object leaves this life. Any per-object clean-up code is placed in the destructor, which must be named <CODECLASS="literal">DESTROY</CODE>.</P><PCLASS="para">Why can't destructors have arbitrary names? Because, although a constructor is explicitly called by name, a destructor is not. Destruction happens automatically via Perl's <ACLASS="indexterm"NAME="ch13-idx-1000004494-0"></A><ACLASS="indexterm"NAME="ch13-idx-1000004494-1"></A>garbage collection (GC) system, which is currently implemented as a quick but lazy reference-based GC system. To know what to call, Perl insists that the destructor be named <CODECLASS="literal">DESTROY</CODE>. If more than one object goes out of scope at once, Perl doesn't promise to call the destructors in a particular order.</P><PCLASS="para">Why is <CODECLASS="literal">DESTROY</CODE> in all caps? Perl on occasion uses purely uppercase function names as a convention to indicate that the function will be automatically called by Perl. Others that are called implicitly include <CODECLASS="literal">BEGIN</CODE>, <CODECLASS="literal">END</CODE>, <CODECLASS="literal">AUTOLOAD</CODE>, plus all methods used by tied objects (see <ACLASS="xref"HREF="ch13_16.htm"TITLE="Creating Magic Variables with tie">Recipe 13.15</A>), like <CODECLASS="literal">STORE</CODE> and <CODECLASS="literal">FETCH</CODE>.</P><PCLASS="para">The user doesn't care when the destructor is called. It just happens when it's supposed to. In languages without any form of GC, this is undependable, so the programmer must explicitly call the destructor to clean up memory and state, crossing their fingers that it's the right time to do so. This is a terrible state of affairs.</P><PCLASS="para">Because of Perl's automatic memory management, an object destructor is rarely needed in Perl. Even when it is, explicit invocation is not only uncalled for, it's downright dangerous. The destructor will be called by the run-time system when the object is no longer in use. Most classes don't need a destructor because Perl takes care of simple matters like memory deallocation.</P><PCLASS="para">The only situation where Perl's reference-based garbage collection system won't work for you is when there's a circularity in your data structure, such as:</P><PRECLASS="programlisting">$self-&gt;{WHATEVER} = $self;</PRE><PCLASS="para">In that case, you must delete the self-reference manually if you expect your program not to leak memory. While admittedly error-prone, this is the best we can do right now. <ACLASS="xref"HREF="ch13_14.htm"TITLE="Coping with Circular Data Structures">Recipe 13.13</A> provides an elegant solution to this problem, however. Nonetheless, rest assured that when your program is finished, its objects' destructors are all duly called. At interpreter shutdown time, a second, more sweeping form of garbage collection is performed. Not even unreachable or circular objects can escape this final destruction. So you are guaranteed that an object <EMCLASS="emphasis">eventually</EM> gets properly destroyed, unless a program never exits. If you're running Perl embedded in another application, the second GC pass happens more frequently  &nbsp;-   whenever an interpreter shuts down.</P><PCLASS="para"><CODECLASS="literal">DESTROY</CODE> does <EMCLASS="emphasis">not</EM> get called when a program exits via an <CODECLASS="literal">exec</CODE> call.<ACLASS="indexterm"NAME="ch13-idx-1000004486-0"></A><ACLASS="indexterm"NAME="ch13-idx-1000004486-1"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch13-pgfId-455">See Also</A></H3><PCLASS="para"><ICLASS="filename">perltoot </I>(1) and <ICLASS="filename">perlobj </I>(1); the section  <ACLASS="olink"HREF="../prog/ch05_03.htm#PERL2-CH-5-SECT-3.9">"A Note on Garbage Collection"</A> in <ACLASS="olink"HREF="../prog/ch05_01.htm">Chapter 5</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A>; <ACLASS="xref"HREF="ch13_11.htm"TITLE="Accessing Overridden Methods">Recipe 13.10</A>; <ACLASS="xref"HREF="ch13_14.htm"TITLE="Coping with Circular Data Structures">Recipe 13.13</A></P></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch13_02.htm"TITLE="13.1. Constructing an Object"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 13.1. Constructing an Object"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch13_04.htm"TITLE="13.3. Managing Instance Data"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 13.3. Managing Instance Data"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">13.1. Constructing an Object</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">13.3. Managing Instance Data</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; Associates. All rights reserved.</font> </p> <map name="library-map"> <area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map> </BODY></HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -