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

📄 mc3.htm

📁 高效c++编程
💻 HTM
📖 第 1 页 / 共 5 页
字号:
  delete theAudioClip;
}
</PRE>
</UL><A NAME="38835"></A>

<A NAME="p52"></A><P><A NAME="dingp36"></A>
The constructor initializes the pointers <CODE>theImage</CODE> and <CODE>theAudioClip</CODE> to null, then makes them point to real objects if the corresponding arguments are non-empty strings. The destructor deletes both pointers, thus ensuring that a <CODE>BookEntry</CODE> object doesn't give rise to a resource leak. Because C++ guarantees it's safe to delete null pointers, <CODE>BookEntry</CODE>'s destructor need not check to see if the pointers actually point to something before deleting <NOBR>them.<SCRIPT>create_link(36);</SCRIPT>
</NOBR></P><A NAME="38864"></A>
<P><A NAME="dingp37"></A>
Everything looks fine here, and under normal conditions everything is fine, but under abnormal conditions &#151; under <I>exceptional</I> conditions &#151; things are not fine at <NOBR>all.<SCRIPT>create_link(37);</SCRIPT>
</NOBR></P><A NAME="69973"></A>
<P><A NAME="dingp38"></A>
Consider what will happen if an exception is thrown during execution of this part of the <CODE>BookEntry</CODE> <NOBR>constructor:<SCRIPT>create_link(38);</SCRIPT>
</NOBR></p>

<A NAME="69974"></A>
<UL><PRE>if (audioClipFileName != "") {
  theAudioClip = new AudioClip(audioClipFileName);
}
</PRE>
</UL><A NAME="69978"></A>

<P><A NAME="dingp39"></A>
An exception might arise because <CODE>operator</CODE> <CODE>new</CODE> (see <A HREF="./MC2_FR.HTM#33985" TARGET="_top" onMouseOver = "self.status = 'Link to MEC++ Item 8'; return true" onMouseOut = "self.status = self.defaultStatus">Item 8</A>) is unable to allocate enough memory for an <CODE>AudioClip</CODE> object. One might also arise because the <CODE>AudioClip</CODE> constructor itself throws an exception. Regardless of the cause of the exception, if one is thrown within the <CODE>BookEntry</CODE> constructor, it will be propagated to the site where the <CODE>BookEntry</CODE> object is being <NOBR>created.<SCRIPT>create_link(39);</SCRIPT>
</NOBR></P><A NAME="38894"></A>
<P><A NAME="dingp40"></A>
Now, if an exception is thrown during creation of the object <CODE>theAudioClip</CODE> is supposed to point to (thus transferring control out of the <CODE>BookEntry</CODE> constructor), who deletes the object that <CODE>theImage</CODE> already points to? The obvious answer is that <CODE>BookEntry</CODE>'s destructor does, but the obvious answer is wrong. <CODE>BookEntry</CODE>'s destructor will never be called. <NOBR>Never.<SCRIPT>create_link(40);</SCRIPT>
</NOBR></P><A NAME="70035"></A>
<P><A NAME="dingp41"></A>
C++ destroys only <I>fully constructed</I> objects, and an object isn't fully constructed until its constructor has run to completion. So if a <CODE>BookEntry</CODE> object <CODE>b</CODE> is created as a local <NOBR>object,<SCRIPT>create_link(41);</SCRIPT>
</NOBR></p>
<A NAME="70036"></A>
<UL><PRE>void testBookEntryClass()
{
  BookEntry b("Addison-Wesley Publishing Company",
              "One Jacob Way, Reading, MA 01867");
<A NAME="38917"></A>
  ...
<A NAME="38918"></A>
}
</PRE>
</UL><A NAME="38895"></A><p><A NAME="dingp42"></A>and an exception is thrown during construction of <CODE>b</CODE>, <CODE>b</CODE>'s destructor will not be called. Furthermore, if you try to take matters into your own hands by allocating <CODE>b</CODE> on the heap and then calling <CODE>delete</CODE> if an exception is <NOBR>thrown,<SCRIPT>create_link(42);</SCRIPT>
</NOBR></P>
<A NAME="38923"></A>
<UL><PRE><A NAME="p53"></A>void testBookEntryClass()
{
  BookEntry *pb = 0;
<A NAME="70472"></A>
  try {
    pb = new BookEntry("Addison-Wesley Publishing Company",
                       "One Jacob Way, Reading, MA 01867");
    ...
  }
  catch (...) {                // catch all exceptions
<A NAME="70015"></A>
     delete pb;                // delete pb when an
                               // exception is thrown
<A NAME="70016"></A>
     throw;                    // propagate exception to
  }                            // caller
<A NAME="38943"></A>
  delete pb;                   // delete pb normally
}
</PRE>
</UL><A NAME="89738"></A><p><A NAME="dingp43"></A>
you'll find that the <CODE>Image</CODE> object allocated inside <CODE>BookEntry</CODE>'s constructor is still lost, because no assignment is made to <CODE>pb</CODE> unless the <CODE>new</CODE> operation succeeds. If <CODE>BookEntry</CODE>'s constructor throws an exception, <CODE>pb</CODE> will be the null pointer, so deleting it in the <CODE>catch</CODE> block does nothing except make you feel better about yourself. Using the smart pointer class <CODE>auto_ptr&lt;BookEntry&gt;</CODE> (see <A HREF="#5292" onMouseOver = "self.status = 'Link to MEC++ Item 9'; return true" onMouseOut = "self.status = self.defaultStatus">Item 9</A>) instead of a raw <CODE>BookEntry*</CODE> won't do you any good either, because the assignment to <CODE>pb</CODE> still won't be made unless the <CODE>new</CODE> operation <NOBR>succeeds.<SCRIPT>create_link(43);</SCRIPT>
</NOBR></p>
<A NAME="38974"></A>
<P><A NAME="dingp44"></A>
There is a reason why C++ refuses to call destructors for objects that haven't been fully constructed, and it's not simply to make your life more difficult. It's because it would, in many cases, be a nonsensical thing &#151; possibly a harmful thing &#151; to do. If a destructor were invoked on an object that wasn't fully constructed, how would the destructor know what to do? The only way it could know would be if bits had been added to each object indicating how much of the constructor had been executed. Then the destructor could check the bits and (maybe) figure out what actions to take. Such bookkeeping would slow down constructors, and it would make each object larger, too. C++ avoids this overhead, but the price you pay is that partially constructed objects aren't automatically destroyed. (For an example of a similar trade-off involving efficiency and program behavior, turn to <A HREF="../EC/EC3_FR.HTM#2117" TARGET="_top" onMouseOver = "self.status = 'Link to EC++ Item 13'; return true" onMouseOut = "self.status = self.defaultStatus">Item E13</A>.)<SCRIPT>create_link(44);</SCRIPT>
</P><A NAME="70098"></A>
<P><A NAME="dingp45"></A>
Because C++ won't clean up after objects that throw exceptions during construction, you must design your constructors so that they clean up after themselves. Often, this involves simply catching all possible exceptions, executing some cleanup code, then rethrowing the exception so it continues to propagate. This strategy can be incorporated into the <CODE>BookEntry</CODE> constructor like <NOBR>this:<SCRIPT>create_link(45);</SCRIPT>
</NOBR></p>
<A NAME="70094"></A>
<UL><PRE><A NAME="p54"></A>
BookEntry::BookEntry(const string&amp; name,
          	     const string&amp; address,
          	     const string&amp; imageFileName,
	      	     const string&amp; audioClipFileName)
: theName(name), theAddress(address),
  theImage(0), theAudioClip(0)
{
  try {                            // this try block is new
    if (imageFileName != "") {
      theImage = new Image(imageFileName);
    }
<A NAME="70041"></A>
    if (audioClipFileName != "") {
      theAudioClip = new AudioClip(audioClipFileName);
    }
  }
  catch (...) {                      // catch any exception
<A NAME="70109"></A>

    delete theImage;                 // perform necessary
    delete theAudioClip;             // cleanup actions
<A NAME="70063"></A>

    throw;                           // propagate the exception
  }
}
</PRE>
</UL><A NAME="39100"></A>

<P><A NAME="dingp46"></A>
There is no need to worry about <CODE>BookEntry</CODE>'s non-pointer data members. Data members are automatically initialized before a class's constructor is called, so if a <CODE>BookEntry</CODE> constructor body begins executing, the object's <CODE>theName</CODE>, <CODE>theAddress</CODE>, and <CODE>thePhones</CODE> data members have already been fully constructed. As fully constructed objects, these data members will be automatically destroyed when the <CODE>BookEntry</CODE> object containing them is, and there is no need for you to intervene. Of course, if these objects' constructors call functions that might throw exceptions, <I>those</I> constructors have to worry about catching the exceptions and performing any necessary cleanup before allowing them to <NOBR>propagate.<SCRIPT>create_link(46);</SCRIPT>
</NOBR></P><A NAME="39092"></A>

<P><A NAME="dingp47"></A>
You may have noticed that the statements in <CODE>BookEntry</CODE>'s <CODE>catch</CODE> block are almost the same as those in <CODE>BookEntry</CODE>'s destructor. Code duplication here is no more tolerable than it is anywhere else, so the best way to structure things is to move the common code into a private helper function and have both the constructor and the destructor call <NOBR>it:<SCRIPT>create_link(47);</SCRIPT>
</NOBR></P><A NAME="39133"></A>
<UL><PRE>class BookEntry {
public:
  ...                      // as before
<A NAME="57468"></A>
private:
  ...
  void cleanup();          // common cleanup statements
};
<A NAME="39159"></A>
<A NAME="p55"></A>void BookEntry::cleanup()
{
  delete theImage;
  delete theAudioClip;
}
<A NAME="70158"></A>
BookEntry::BookEntry(const string&amp; name,
                     const string&amp; address,
         	     const string&amp; imageFileName,
          	     const string&amp; audioClipFileName)
: theName(name), theAddress(address),
  theImage(0), theAudioClip(0)
{
  try {
    ...                   // as before
  }
  catch (...)   {
    cleanup();            // release resources
    throw;                // propagate exception
  }
}
<A NAME="39165"></A>
BookEntry::~BookEntry()
{
  cleanup();
}
</PRE>
</UL><A NAME="39157"></A>
<P><A NAME="dingp48"></A>
This is nice, but it doesn't put the topic to rest. Let us suppose we design our <CODE>BookEntry</CODE> class slightly differently so that <CODE>theImage</CODE> and <CODE>theAudioClip</CODE> are <I>constant</I> <NOBR>pointers:<SCRIPT>create_link(48);</SCRIPT>
</NOBR></p>

<A NAME="70192"></A>
<UL><PRE>class BookEntry {
public:
  ...                                  // as above
<A NAME="39225"></A>
private:
  ...
  Image * const theImage;              // pointers are now
  AudioClip * const theAudioClip;      // const
};
</PRE>
</UL><A NAME="39253"></A>

<P><A NAME="dingp49"></A>
Such pointers must be initialized via the member initialization lists of <CODE>BookEntry</CODE>'s constructors, because there is no other way to give <CODE>const</CODE> pointers a value (see <A HREF="../EC/EC3_FR.HTM#2071" TARGET="_top" onMouseOver = "self.status = 'Link to EC++ Item 12'; return true" onMouseOut = "self.status = self.defaultStatus">Item E12</A>). A common temptation is to initialize <CODE>theImage</CODE> and <CODE>theAudioClip</CODE> like <NOBR>this,<SCRIPT>create_link(49);</SCRIPT>
</NOBR></p>
<A NAME="39262"></A>
<UL><PRE><A NAME="p56"></A>// an implementation that may leak resources if an
// exception is thrown
BookEntry::BookEntry(const string&amp; name,
                     const string&amp; address,
                     const string&amp; imageFileName,
                     const string&amp; audioClipFileName)
: theName(name), theAddress(address),
  theImage(imageFileName != ""
           ? new Image(imageFileName)
           : 0),
  theAudioClip(audioClipFileName != ""

⌨️ 快捷键说明

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