📄 ec3.htm
字号:
<BR>Continue to <A HREF="#223029">Item 14: Make sure base classes have virtual destructors.</A></FONT></DIV>
<P><A NAME="dingp43"></A><FONT ID="eititle">Item 13: List members in an initialization list in the order in which they are declared.</FONT><SCRIPT>create_link(43);</SCRIPT>
</P>
<P><A NAME="dingp44"></A>
Unrepentant Pascal and Ada programmers often yearn for the ability to define arrays with arbitrary bounds, i.e., from 10 to 20 instead of from 0 to 10. Long-time C programmers will insist that everybody who's anybody will always start counting from 0, but it's easy enough to placate the <CODE>begin</CODE>/<CODE>end</CODE> crowd. All you have to do is define your own <CODE>Array</CODE> class <NOBR>template:<SCRIPT>create_link(44);</SCRIPT>
</NOBR></P>
<A NAME="2119"></A>
<UL><PRE>template<class T>
class Array {
public:
Array(int lowBound, int highBound);
...
</PRE>
</UL><A NAME="28479"></A>
<UL><PRE>private:
vector<T> data; // the array data is stored
// in a vector object; see
// <A HREF="./EC7_FR.HTM#8392" TARGET="_top">Item 49</A> for info about
// the vector template
</PRE>
</UL><A NAME="16656"></A>
<UL><PRE>
size_t size; // # of elements in array
</PRE>
</UL><A NAME="16657"></A>
<UL><PRE>
int lBound, hBound; // lower bound, higher bound
};
</PRE>
</UL><A NAME="16663"></A>
<UL><PRE>template<class T>
Array<T>::Array(int lowBound, int highBound)
: size(highBound - lowBound + 1),
lBound(lowBound), hBound(highBound),
data(size)
{}
</PRE>
</UL><p><A NAME="2122"></A>
<P><A NAME="dingp45"></A>
An industrial-strength constructor would perform sanity checking on its parameters to ensure that <CODE>highBound</CODE> was at least as great as <CODE>lowBound</CODE>, but there is a much nastier error here: even with perfectly good <A NAME="p58"></A>values for the array's bounds, you have absolutely no idea how many elements <CODE>data</CODE> <NOBR>holds.<SCRIPT>create_link(45);</SCRIPT>
</NOBR></P>
<A NAME="2123"></A>
<P><A NAME="dingp46"></A>
"How can that be?" I hear you cry. "I carefully initialized <CODE>size</CODE> before passing it to the <CODE>vector</CODE> constructor!" Unfortunately, you didn't — you just tried to. The rules of the game are that class members are initialized <I>in the order of their declaration in the class</I>; the order in which they are listed in a member initialization list makes not a whit of difference. In the classes generated by your <CODE>Array</CODE> template, <CODE>data</CODE> will always be initialized first, followed by <CODE>size</CODE>, <CODE>lBound</CODE>, and <CODE>hBound</CODE>. <NOBR>Always.<SCRIPT>create_link(46);</SCRIPT>
</NOBR></P>
<A NAME="2124"></A>
<P><A NAME="dingp47"></A>
Perverse though this may seem, there is a reason for it. Consider this <NOBR>scenario:<SCRIPT>create_link(47);</SCRIPT>
</NOBR></P>
<A NAME="2125"></A>
<UL><PRE>class Wacko {
public:
Wacko(const char *s): s1(s), s2(0) {}
Wacko(const Wacko& rhs): s2(rhs.s1), s1(0) {}
</PRE>
</UL><A NAME="28487"></A>
<UL><PRE>private:
string s1, s2;
};
</PRE>
</UL><A NAME="2127"></A>
<UL><PRE>Wacko w1 = "Hello world!";
Wacko w2 = w1;
</PRE>
</UL><A NAME="2128"></A>
<P><A NAME="dingp48"></A>
If members were initialized in the order of their appearance in an initialization list, the data members of <CODE>w1</CODE> and <CODE>w2</CODE> would be constructed in different orders. Recall that the destructors for the members of an object are always called in the inverse order of their constructors. Thus, if the above were allowed, compilers would have to keep track of the order in which the members were initialized for <I>each object</I>, just to ensure that the destructors would be called in the right order. That would be an expensive proposition. To avoid that overhead, the order of construction and destruction is the same for all objects of a given type, and the order of members in an initialization list is <NOBR>ignored.<SCRIPT>create_link(48);</SCRIPT>
</NOBR></P>
<A NAME="2129"></A>
<P><A NAME="dingp49"></A>
Actually, if you really want to get picky about it, only nonstatic data members are initialized according to the rule. Static data members act like global and namespace objects, so they are initialized only once; see <A HREF="./EC7_FR.HTM#8299" TARGET="_top">Item 47</A> for details. Furthermore, base class data members are initialized before derived class data members, so if you're using inheritance, you should list base class initializers at the very beginning of your member initialization lists. (If you're using <I>multiple</I> inheritance, your base classes will be initialized in the order in which you <I>inherit</I> from them; the order in which they're listed in your member initialization lists will again be ignored. However, if you're using multiple inheritance, you've probably got more important things to worry about. If you <A NAME="p59"></A>don't, <A HREF="./EC6_FR.HTM#7778" TARGET="_top">Item 43</A> would be happy to make suggestions regarding aspects of multiple inheritance that are <NOBR>worrisome.)<SCRIPT>create_link(49);</SCRIPT>
</NOBR></P>
<A NAME="2130"></A>
<P><A NAME="dingp50"></A>
The bottom line is this: if you hope to understand what is really going on when your objects are initialized, be sure to list the members in an initialization list in the order in which those members are declared in the <NOBR>class.<SCRIPT>create_link(50);</SCRIPT>
</NOBR></P>
<!-- SectionName="E14: Make sure base classes have virtual dtors" -->
<A NAME="223029"></A><A NAME="2132"></A><DIV ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="#2117">Item 13: List members in an initialization list in the order in which they are declared.</A>
<BR>Continue to <A HREF="#2182">Item 15: Have operator= return a reference to *this.</A></FONT></DIV>
<P><A NAME="dingp51"></A><FONT ID="eititle">Item 14: Make sure base classes have virtual destructors.</FONT><SCRIPT>create_link(51);</SCRIPT>
</P>
<P><A NAME="dingp52"></A>
Sometimes it's convenient for a class to keep track of how many objects of its type exist. The straightforward way to do this is to create a static class member for counting the objects. The member is initialized to 0, is incremented in the class constructors, and is decremented in the class destructor. (<A HREF="../MEC/MC5_FR.HTM#5350" TARGET="_top">Item M26</A> shows how to package this approach so it's easy to add to any class, and <A HREF="../MAGAZINE/CO_FRAME.HTM" TARGET="_top">my article on counting objects</A> describes additional refinements to the <NOBR>technique.)<SCRIPT>create_link(52);</SCRIPT>
</NOBR></P>
<A NAME="2133"></A>
<P><A NAME="dingp53"></A>
You might envision a military application, in which a class representing enemy targets might look something like <NOBR>this:<SCRIPT>create_link(53);</SCRIPT>
</NOBR></P>
<A NAME="2134"></A>
<UL><PRE>class EnemyTarget {
public:
EnemyTarget() { ++numTargets; }
EnemyTarget(const EnemyTarget&) { ++numTargets; }
~EnemyTarget() { --numTargets; }
</PRE>
</UL><A NAME="29358"></A>
<UL><PRE> static size_t numberOfTargets()
{ return numTargets; }
</PRE>
</UL><A NAME="2137"></A>
<UL><PRE>
virtual bool destroy(); // returns success of
// attempt to destroy
// EnemyTarget object
</PRE>
</UL><A NAME="28495"></A>
<UL><PRE>private:
static size_t numTargets; // object counter
};
</PRE>
</UL><A NAME="2138"></A>
<UL><PRE>// class statics must be defined outside the class;
// initialization is to 0 by default
size_t EnemyTarget::numTargets;
</PRE>
</UL><A NAME="2139"></A>
<P><A NAME="dingp54"></A>
This class is unlikely to win you a government defense contract, but it will suffice for our purposes here, which are substantially less demanding than are those of the Department of Defense. Or so we may <NOBR>hope.<SCRIPT>create_link(54);</SCRIPT>
</NOBR></P>
<A NAME="2140"></A>
<P><A NAME="dingp55"></A>
Let us suppose that a particular kind of enemy target is an enemy tank, which you model, naturally enough (see <A HREF="./EC6_FR.HTM#6914" TARGET="_top">Item 35</A>, but also see <A HREF="../MEC/MC6_FR.HTM#10947" TARGET="_top">Item M33</A>), as a publicly derived class of <CODE>EnemyTarget</CODE>. Because you are interested in the total number of enemy tanks as well as the total <A NAME="p60"></A>number of enemy targets, you'll pull the same trick with the derived class that you did with the base <NOBR>class:<SCRIPT>create_link(55);</SCRIPT>
</NOBR></P>
<A NAME="2141"></A>
<UL><PRE>class EnemyTank: public EnemyTarget {
public:
EnemyTank() { ++numTanks; }
</PRE>
</UL><A NAME="15156"></A>
<UL><PRE> EnemyTank(const EnemyTank& rhs)
: EnemyTarget(rhs)
{ ++numTanks; }
</PRE>
</UL><A NAME="5525"></A>
<UL><PRE> ~EnemyTank() { --numTanks; }
</PRE>
</UL><A NAME="2143"></A>
<UL><PRE> static size_t numberOfTanks()
{ return numTanks; }
</PRE>
</UL><A NAME="28501"></A>
<UL><PRE> virtual bool destroy();
</PRE>
</UL><A NAME="28502"></A>
<UL><PRE>private:
static size_t numTanks; // object counter for tanks
};
</PRE>
</UL><A NAME="2145"></A>
<P><A NAME="dingp56"></A>
Having now added this code to two different classes, you may be in a better position to appreciate <A HREF="../MEC/MC5_FR.HTM#5350" TARGET="_top">Item M26</A>'s general solution to the <NOBR>problem.<SCRIPT>create_link(56);</SCRIPT>
</NOBR></P>
<A NAME="222037"></A>
<P><A NAME="dingp57"></A>
Finally, let's assume that somewhere in your application, you dynamically create an <CODE>EnemyTank</CODE> object using <CODE>new</CODE>, which you later get rid of via <CODE>delete</CODE>:<SCRIPT>create_link(57);</SCRIPT>
</P>
<A NAME="2146"></A>
<UL><PRE>EnemyTarget *targetPtr = new EnemyTank;
</PRE>
</UL><A NAME="2147"></A>
<UL><PRE>...
</PRE>
</UL><A NAME="2148"></A>
<UL><PRE>delete targetPtr;
</PRE>
</UL><A NAME="2149"></A>
<P><A NAME="dingp58"></A>
Everything you've done so far seems completely kosher. Both classes undo in the destructor what they did in the constructor, and there's certainly nothing wrong with your application, in which you were careful to use <CODE>delete</CODE> after you were done with the object you conjured up with <CODE>new</CODE>. Nevertheless, there is something very troubling here. Your program's behavior is <I>undefined</I> — you have no way of knowing what will <NOBR>happen.<SCRIPT>create_link(58);</SCRIPT>
</NOBR></P>
<A NAME="2150"></A>
<P><A NAME="dingp59"></A>
The <NOBR><FONT COLOR="#FF0000" SIZE="-2"><B>°</B></FONT><A HREF="http://www.awl.com/cseng/cgi-bin/cdquery.pl?name=cstandard" onMouseOver = "self.status = 'The latest publicly-available version of the C++ standard'; return true" onMouseOut = "self.status = self.defaultStatus" TARGET="_top">C++</NOBR> language standard</A> is unusually clear on this topic. When you try to delete a derived class object through a base class pointer and the base class has a nonvirtual destructor (as <CODE>EnemyTarget</CODE> does), the results are undefined. That means compilers may generate code to do whatever they like: reformat your disk, send suggestive mail to your boss, fax source code to your competitors, whatever. (What often happens at runtime is that the derived class's destructor is never called. In this example, that would mean your count of <CODE>EnemyTank</CODE>s would not be adjusted when <CODE>targetPtr</CODE> was deleted. Your count of enemy tanks would thus be wrong, a rather disturbing prospect to combatants dependent on accurate battlefield <NOBR>information.)<SCRIPT>create_link(59);</SCRIPT>
</NOBR></P>
<A NAME="2151"></A>
<P><A NAME="dingp60"></A>
<A NAME="p61"></A>To avoid this problem, you have only to make the <CODE>EnemyTarget</CODE> destructor <I>virtual</I>. Declaring the destructor virtual ensures well-defined behavior that does precisely what you want: both <CODE>EnemyTank</CODE>'s and <CODE>EnemyTarget</CODE>'s destructors will be called before the memory holding the object is <NOBR>deallocated.<SCRIPT>create_link(60);</SCRIPT>
</NOBR></P>
<A NAME="2152"></A>
<P><A NAME="dingp61"></A>
Now, the <CODE>EnemyTarget</CODE> class contains a virtual function, which is generally the case with base classes. After all, the purpose of virtual functions is to allow customization of behavior in derived classes (see <A HREF="./EC6_FR.HTM#7007" TARGET="_top">Item 36</A>), so almost all base classes contain virtual <NOBR>functions.<SCRIPT>create_link(61);</SCRIPT>
</NOBR></P>
<A NAME="2153"></A>
<P><A NAME="dingp62"></A>
If a class does <I>not</I> contain any virtual functions, that is often an indication that it is not meant to be used as a base class. When a class is not intended to be used as a base class, making the destructor virtual is usually a bad idea. Consider this example, based on a discussion in the ARM (see <A HREF="./EC7_FR.HTM#8569" TARGET="_top">Item 50</A>):<SCRIPT>create_link(62);</SCRIPT>
</P>
<A NAME="2154"></A>
<UL><PRE>// class for representing 2D points
class Point {
public:
Point(short int xCoord, short int yCoord);
~Point();
</PRE>
</UL><A NAME="28510"></A>
<UL><PRE>private:
short int x, y;
};
</PRE>
</UL><A NAME="2156"></A>
<P><A NAME="dingp63"></A>
If a <CODE>short</CODE> <CODE>int</CODE> occupies 16 bits, a <CODE>Point</CODE> object can fit into a 32-bit register. Furthermore, a <CODE>Point</CODE> object can be passed as a 32-bit quantity to functions written in other languages such as C or FORTRAN. If <CODE>Point</CODE>'s destructor is made virtual, however, the situation <NOBR>changes.<SCRIPT>create_link(63);</SCRIPT>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -