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

📄 mi3.htm

📁 一个非常适合初学者入门的有关c++的文档
💻 HTM
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN" "http://www.w3.org/TR/REC-html40/frameset.dtd">
<HTML LANG="EN">
<HEAD>
<TITLE>More Effective C++ | Item 3: Never treat arrays polymorphically</TITLE>
<LINK REL=STYLESHEET HREF=../INTRO/ECMEC.CSS>

<SCRIPT LANGUAGE="Javascript" SRC="../JAVA/COOKIE.JS"></SCRIPT>
<SCRIPT LANGUAGE="Javascript">var imagemax = 0; setCurrentMax(0);</SCRIPT>
<SCRIPT LANGUAGE="Javascript" SRC="../JAVA/DINGBATS.JS"></SCRIPT>
<SCRIPT LANGUAGE="Javascript">
var dingbase = "MI3_DIR.HTM";
var dingtext = "Item M3, P";
if (self == top) {
 top.location.replace(dingbase + this.location.hash);
}</SCRIPT>

</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" ONLOAD="setResize()">

<!-- SectionName="M3: Never treat arrays polymorphically" -->
<A NAME="84818"></A>
<DIV ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="./MI2_FR.HTM" TARGET="_top">Item 2: Prefer C++-style casts</A> &nbsp;&nbsp;<BR>&nbsp;&nbsp;Continue to <A HREF="./MI4_FR.HTM" TARGET="_top">Item 4: Avoid gratuitous default constructors</A></FONT></DIV>


<P><A NAME="dingp1"></A><font ID="mititle">Item 3: &nbsp;Never treat arrays polymorphically.</font><SCRIPT>create_link(1);</SCRIPT>
</P>

<A NAME="72107"></A>

<A NAME="31585"></A>
<P><A NAME="dingp2"></A>
One of the most important features of inheritance is that you can manipulate derived class objects through pointers and references to base class objects. Such pointers and references are said to behave <I>polymorphically</I> &#151; as if they had multiple types. C++ also allows you to manipulate <I>arrays</I> of derived class objects through base class pointers and references. This is no feature at all, because it almost never works the way you want it <NOBR>to.<SCRIPT>create_link(2);</SCRIPT>
</NOBR></P><A NAME="77400"></A>
<P><A NAME="dingp3"></A>
For example, suppose you have a class <CODE>BST</CODE> (for binary search tree objects) and a second class, <CODE>BalancedBST</CODE>, that inherits from <CODE>BST</CODE>:<SCRIPT>create_link(3);</SCRIPT>
</P>
<A NAME="77401"></A>
<UL><PRE>class BST { ... };
<A NAME="77402"></A>
class BalancedBST: public BST { ... };</PRE>
</UL>
<A NAME="77403"></A>
<P><A NAME="dingp4"></A>
In a real program such classes would be templates, but that's unimportant here, and adding all the template syntax just makes things harder to read. For this discussion, we'll assume <CODE>BST</CODE> and <CODE>BalancedBST</CODE> objects contain only <CODE>int</CODE>s.<SCRIPT>create_link(4);</SCRIPT>
</P><A NAME="77404"></A>
<P><A NAME="dingp5"></A>
Consider a function to print out the contents of each <CODE>BST</CODE> in an array of <CODE>BST</CODE>s:<SCRIPT>create_link(5);</SCRIPT>
</P><A NAME="77406"></A>
<UL><A NAME="p17"></A>
<PRE>
void printBSTArray(ostream&amp; s,
                   const BST array[],
                   int numElements)
{
  for (int i = 0; i &lt; numElements; ++i) {
    s &lt;&lt; array[i];              // this assumes an
  }                             // operator&lt;&lt; is defined
}                               // for BST objects
</PRE>
</UL>
<A NAME="77407"></A>
<P><A NAME="dingp6"></A>
This will work fine when you pass it an array of <CODE>BST</CODE> <NOBR>objects:<SCRIPT>create_link(6);</SCRIPT>
</NOBR></P><A NAME="77408"></A>
<UL><PRE>BST BSTArray[10];
<A NAME="77409"></A>
...
<A NAME="77410"></A>
printBSTArray(cout, BSTArray, 10);          // works fine</PRE>
</UL>
<A NAME="77411"></A>
<P><A NAME="dingp7"></A>
Consider, however, what happens when you pass <CODE>printBSTArray</CODE> an array of <CODE>BalancedBST</CODE> <NOBR>objects:<SCRIPT>create_link(7);</SCRIPT>
</NOBR></P><A NAME="77412"></A>
<UL><PRE>BalancedBST bBSTArray[10];
<A NAME="77413"></A>
...
<A NAME="77414"></A>
printBSTArray(cout, bBSTArray, 10);         // works fine?</PRE>
</UL>
<A NAME="77415"></A>
<P><A NAME="dingp8"></A>
Your compilers will accept this function call without complaint, but look again at the loop for which they must generate <NOBR>code:<SCRIPT>create_link(8);</SCRIPT>
</NOBR></P><A NAME="77416"></A>
<UL><PRE>for (int i = 0; i &lt; numElements; ++i) {
  s &lt;&lt; array[i];
}</PRE>
</UL>
<A NAME="77417"></A>
<P><A NAME="dingp9"></A>
Now, <CODE>array[i]</CODE> is really just shorthand for an expression involving pointer arithmetic: it stands for <CODE>*(array+i)</CODE>. We know that <CODE>array</CODE> is a pointer to the beginning of the array, but how far away from the memory location pointed to by <CODE>array</CODE> is the memory location pointed to by <CODE>array+i</CODE>? The distance between them is <CODE>i*sizeof(<I>an</I></CODE> <CODE><I>object</I></CODE> <CODE><I>in</I></CODE> <CODE><I>the</I></CODE> <CODE><I>array</I></CODE><CODE>)</CODE>, because there are <CODE>i</CODE> objects between <CODE>array[0]</CODE> and <CODE>array[i]</CODE>. In order for compilers to emit code that walks through the array correctly, they must be able to determine the size of the objects in the array. This is easy for them to do. The parameter <CODE>array</CODE> is declared to be of type array-of-<CODE>BST</CODE>, so each element of the array must be a <CODE>BST</CODE>, and the distance between <CODE>array</CODE> and <CODE>array+i</CODE> must be <CODE>i*sizeof(BST)</CODE>.<SCRIPT>create_link(9);</SCRIPT>
</P><A NAME="77418"></A>
<P><A NAME="dingp10"></A>
At least that's how your compilers look at it. But if you've passed an array of <CODE>BalancedBST</CODE> objects to <CODE>printBSTArray</CODE>, your compilers are probably wrong. In that case, they'd assume each object in the array is the size of a <CODE>BST</CODE>, but each object would actually be the size of a <CODE>BalancedBST</CODE>. Derived classes usually have more data members than their base classes, so derived class objects are usually larger than base class objects. We thus expect a <CODE>BalancedBST</CODE> object to be larger than a <A NAME="p18"></A><CODE>BST</CODE> object. If it is, the pointer arithmetic generated for <CODE>printBSTArray</CODE> will be wrong for arrays of <CODE>BalancedBST</CODE> objects, and there's no telling what will happen when <CODE>printBSTArray</CODE> is invoked on a <CODE>BalancedBST</CODE> array. Whatever does happen, it's a good bet it won't be <NOBR>pleasant.<SCRIPT>create_link(10);</SCRIPT>
</NOBR></P><A NAME="77419"></A>
<P><A NAME="dingp11"></A>
The problem pops up in a different guise if you try to delete an array of derived class objects through a base class pointer. Here's one way you might innocently attempt to do <NOBR>it:<SCRIPT>create_link(11);</SCRIPT>
</NOBR></P>
<A NAME="77420"></A>
<UL><PRE>// delete an array, but first log a message about its
// deletion
void deleteArray(ostream&amp; logStream, BST array[])
{
  logStream &lt;&lt; "Deleting array at address "
            &lt;&lt; static_cast&lt;void*&gt;(array) &lt;&lt; '\n';
<A NAME="77421"></A>
delete [] array;
}
<A NAME="77422"></A>
<CODE>BalancedBST</CODE> *balTreeArray =                  // create a <CODE>BalancedBST</CODE>
  new <CODE>BalancedBST</CODE>[50];                       // array
<A NAME="77423"></A>
...
<A NAME="77424"></A>
deleteArray(cout, balTreeArray);             // log its deletion</PRE>
</UL>
<A NAME="77425"></A>
<P><A NAME="dingp12"></A>
You can't see it, but there's pointer arithmetic going on here, too. When an array is deleted, a destructor for each element of the array must be called (see <a href="./MI8_FR.HTM#33985" TARGET="_top">Item 8</A>). When compilers see the <NOBR>statement<SCRIPT>create_link(12);</SCRIPT>
</NOBR></P>
<A NAME="77429"></A>
<UL><PRE>delete [] array;</PRE>
</UL>
<A NAME="77430"></A>
<P><A NAME="dingp13"></A>they must generate code that does something like <NOBR>this:<SCRIPT>create_link(13);</SCRIPT>
</NOBR></P>
<A NAME="77431"></A>
<UL><PRE>// destruct the objects in *array in the inverse order
// in which they were constructed
for (        int i = <I>the number of elements in the array - 1</I>;
        i &gt;= 0;
        --i)
  {
    array[i].BST::~BST();                     // call array[i]'s
  }                                           // destructor</PRE>
</UL>
<A NAME="77432"></A>
<P><A NAME="dingp14"></A>
Just as this kind of loop failed to work when you wrote it, it will fail to work when your compilers write it, too. The <NOBR><FONT COLOR="#FF0000" SIZE="-2"><B>&deg;</B></FONT><A HREF="http://www.awl.com/cseng/cgi-bin/cdquery.pl?name=cstandard" onMouseOver="self.status='ISO/ANSI standard for C++'; return true" onMouseOut="self.status=self.defaultStatus" target="_top">language</NOBR> specification</A> says the result of deleting an array of derived class objects through a base class pointer is undefined, but we know what that really means: executing the code is almost certain to lead to grief. Polymorphism and pointer arithmetic simply don't mix. Array operations almost always involve pointer arithmetic, so arrays and polymorphism don't <NOBR>mix.<SCRIPT>create_link(14);</SCRIPT>
</NOBR></P><A NAME="92807"></A>
<P><A NAME="dingp15"></A>
Note that you're unlikely to make the mistake of treating an array polymorphically if you avoid having a concrete class (like <CODE>BalancedBST</CODE>) in<A NAME="p19"></A>herit from another concrete class (such as <CODE>BST</CODE>). As <a href="./MI33_FR.HTM#10947" TARGET="_top">Item 33</A> explains, designing your software so that concrete classes never inherit from one another has many benefits. I encourage you to turn to <a href="./MI33_FR.HTM#10947" TARGET="_top">Item 33</A> and read all about <NOBR>them.<SCRIPT>create_link(15);</SCRIPT>
</NOBR></P>

<DIV ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="./MI2_FR.HTM" TARGET="_top">Item 2: Prefer C++-style casts</A> &nbsp;&nbsp;<BR>&nbsp;&nbsp;Continue to <A HREF="./MI4_FR.HTM" TARGET="_top">Item 4: Avoid gratuitous default constructors</A></FONT></DIV>

</BODY>
</HTML>

⌨️ 快捷键说明

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