📄 mcintro.htm
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN" "http://www.w3.org/TR/REC-html40/frameset.dtd">
<HTML LANG="EN">
<HEAD><H5></H5>
<TITLE>More Effective C++ | Introduction</TITLE>
<LINK REL=STYLESHEET HREF=../INTRO/ECMEC.CSS>
<SCRIPT LANGUAGE="Javascript" SRC="../JAVA/COOKIE.JS"></SCRIPT>
<SCRIPT LANGUAGE="Javascript">var imagemax = 2; setCurrentMax(2);</SCRIPT>
<SCRIPT LANGUAGE="Javascript" SRC="../JAVA/IMGDOC.JS"></SCRIPT>
<SCRIPT LANGUAGE="Javascript" SRC="../JAVA/NSIMGDOC.JS"></SCRIPT>
<SCRIPT LANGUAGE="Javascript" SRC="../JAVA/DINGBATS.JS"></SCRIPT>
<SCRIPT>
var dingbase = "MCINTRDR.HTM";
var dingtext = "MEC++ Intro, P";
if (self == top) {
top.location.replace(dingbase + this.location.hash);
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" ONLOAD="setResize()">
<!-- SectionName="MEC++ Introduction" -->
<DIV ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="./MCACK_FR.HTM" TARGET="_top">Acknowledgments</A> <BR> Continue to <A HREF="./MC1_FR.HTM" TARGET="_top">Chapter 1: Basics</A></FONT></DIV>
<A NAME="p1"></A>
<P><A NAME="dingp1"></A><font ID="mgtitle">Introduction</font><SCRIPT>create_link(1);</SCRIPT>
</P>
<A NAME="1708"> </A>
<p><A NAME="dingp2"></A><A NAME="73953"> </A>
These are heady days for C++ programmers. Commercially available less than a decade, C++ has nevertheless emerged as the language of choice for systems programming on nearly all major computing platforms. Companies and individuals with challenging programming problems increasingly embrace the language, and the question faced by those who do not use C++ is often <I>when</I> they will start, not <I>if</I>. Standardization of C++ is complete, and the breadth and scope of the accompanying <a href="../EC/EC7_FR.HTM#8392" target="_top">library</a> — which both dwarfs and subsumes that of C — makes it possible to write rich, complex programs without sacrificing portability or implementing common algorithms and data structures from scratch. C++ compilers continue to proliferate, the features they offer continue to expand, and the quality of the code they generate continues to improve. Tools and environments for C++ development grow ever more abundant, powerful, and robust. Commercial libraries all but obviate the need to write code in many application <NOBR>areas.<SCRIPT>create_link(2);</SCRIPT>
</NOBR></P><A NAME="71383"> </A>
<P><A NAME="dingp3"></A>
As the language has matured and our experience with it has increased, our needs for information about it have changed. In 1990, people wanted to know <I>what</I> C++ was. By 1992, they wanted to know <I>how</I> to make it work. Now C++ programmers ask higher-level questions: How can I design my software so it will adapt to future demands? How can I improve the efficiency of my code without compromising its correctness or making it harder to use? How can I implement sophisticated functionality not directly supported by the <NOBR>language?<SCRIPT>create_link(3);</SCRIPT>
</NOBR></P><A NAME="72559"> </A>
<P><A NAME="dingp4"></A>
In this book, I answer these questions and many others like <NOBR>them.<SCRIPT>create_link(4);</SCRIPT>
</NOBR></P><A NAME="71453"> </A>
<P><A NAME="dingp5"></A>
This book shows how to design and implement C++ software that is <I>more effective</I>: more likely to behave correctly; more robust in the face of exceptions; more efficient; more portable; makes better use of language features; adapts to change more gracefully; works better in a mixed-language environment; is easier to use correctly; is harder to use incorrectly. In short, software that's just <I>better</I>.<SCRIPT>create_link(5);</SCRIPT>
</P><A NAME="74649"> </A>
<P><A NAME="dingp6"></A>
<A NAME="p2"></A>The material in this book is divided into 35 Items. Each Item summarizes accumulated wisdom of the C++ programming community on a particular topic. Most Items take the form of guidelines, and the explanation accompanying each guideline describes why the guideline exists, what happens if you fail to follow it, and under what conditions it may make sense to violate the guideline <NOBR>anyway.<SCRIPT>create_link(6);</SCRIPT>
</NOBR></P><A NAME="72734"> </A>
<P><A NAME="dingp7"></A>
Items fall into several categories. Some concern particular language features, especially newer features with which you may have little experience. For example, Items <A HREF="./MC3_FR.HTM#5292" TARGET="_top">9</A> through <A HREF="./MC3_FR.HTM#40989" TARGET="_top">15</A> are devoted to exceptions (as are the <A HREF="../MAGAZINE/INDEX.HTM" TARGET="_top">magazine articles</A> by Tom Cargill, Jack Reeves, and Herb Sutter). Other Items explain how to combine the features of the language to achieve higher-level goals. Items <A HREF="./MC5_FR.HTM#5341" TARGET="_top">25</A> through <A HREF="./MC5_FR.HTM#34883" TARGET="_top">31</A>, for instance, describe how to constrain the number or placement of objects, how to create functions that act "virtual" on the type of more than one object, how to create "smart pointers," and more. Still other Items address broader topics; Items <A HREF="./MC4_FR.HTM#40995" TARGET="_top">16</A> through <A HREF="./MC4_FR.HTM#41284" TARGET="_top">24</A> focus on efficiency. No matter what the topic of a particular Item, each takes a no-nonsense approach to the subject. In <A HREF="./INDEX.HTM" TARGET="_top"><I>More Effective C++</I></A>, you learn how to <I>use</I> C++ more effectively. The descriptions of language features that make up the bulk of most C++ texts are in this book mere background <NOBR>information.<SCRIPT>create_link(7);</SCRIPT>
</NOBR></P><A NAME="48627"> </A>
<P><A NAME="dingp8"></A>
An implication of this approach is that you should be familiar with C++ before reading this book. I take for granted that you understand classes, protection levels, virtual and nonvirtual functions, etc., and I assume you are acquainted with the concepts behind templates and exceptions. At the same time, I don't expect you to be a language expert, so when poking into lesser-known corners of C++, I always explain what's going <NOBR>on.<SCRIPT>create_link(8);</SCRIPT>
</NOBR></p>
<P><A NAME="dingp9"></A><font ID="mhtitle">The C++ in <i>More Effective C++</i></font><SCRIPT>create_link(9);</SCRIPT>
</P>
<A NAME="73855"> </A>
<P><A NAME="dingp10"></A>
The C++ I describe in this book is the language specified by 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 = 'C++ Language Standard Home Page'; return true" onMouseOut = "self.status = self.defaultStatus" target="_top">Final</NOBR> Draft International Standard</A> of the <NOBR><FONT COLOR="#FF0000" SIZE="-2"><B>°</B></FONT><A HREF="http://www.awl.com/cseng/cgi-bin/cdquery.pl?name=committee" onMouseOver="self.status='ISO/ANSI Standardization Committee Home Page'; return true" onMouseOut="self.status=self.defaultStatus" target="_top">ISO/ANSI</NOBR> standardization committee</A> in November 1997. In all likelihood, this means I use a few features your compilers don't yet support. Don't worry. The only "new" feature I assume you have is templates, and templates are now almost universally available. I use exceptions, too, but that use is largely confined to Items <A HREF="./MC3_FR.HTM#5292" TARGET="_top">9</A> through <A HREF="./MC3_FR.HTM#40989" TARGET="_top">15</A>, which are specifically devoted to exceptions. If you don't have access to a compiler offering exceptions, that's okay. It won't affect your ability to take advantage of the material in the other parts of the book. Furthermore, you should read Items <A HREF="./MC3_FR.HTM#5292" TARGET="_top">9</A> through <A HREF="./MC3_FR.HTM#40989" TARGET="_top">15</A> even if you don't have support for exceptions, because those items (as well as the <A HREF="../MAGAZINE/INDEX.HTM" TARGET="_top">associated articles</A>) examine issues you need to understand in any <NOBR>case.<SCRIPT>create_link(10);</SCRIPT>
</NOBR></P><A NAME="73315"> </A>
<P><A NAME="dingp11"></A>
I recognize that just because the standardization committee blesses a feature or endorses a practice, there's no guarantee that the feature is present in current compilers or the practice is applicable to existing <A NAME="p3"></A>environments. When faced with a discrepancy between theory (what the committee says) and practice (what actually works), I discuss both, though my bias is toward things that work. Because I discuss both, this book will aid you as your compilers approach conformance with the standard. It will show you how to use existing constructs to approximate language features your compilers don't yet support, and it will guide you when you decide to transform workarounds into newly- supported <NOBR>features.<SCRIPT>create_link(11);</SCRIPT>
</NOBR></P><A NAME="48772"> </A>
<P><A NAME="dingp12"></A>
Notice that I refer to your <I>compilers </I>— plural. Different compilers implement varying approximations to the standard, so I encourage you to develop your code under at least two compilers. Doing so will help you avoid inadvertent dependence on one vendor's proprietary language extension or its misinterpretation of the standard. It will also help keep you away from the bleeding edge of compiler technology, e.g., from new features supported by only one vendor. Such features are often poorly implemented (buggy or slow — frequently both), and upon their introduction, the C++ community lacks experience to advise you in their proper use. Blazing trails can be exciting, but when your goal is producing reliable code, it's often best to let others test the waters before jumping <NOBR>in.<SCRIPT>create_link(12);</SCRIPT>
</NOBR></P><A NAME="71704"> </A>
<P><A NAME="dingp13"></A>
There are two constructs you'll see in this book that may not be familiar to you. Both are relatively recent language extensions. Some compilers support them, but if your compilers don't, you can easily approximate them with features you do <NOBR>have.<SCRIPT>create_link(13);</SCRIPT>
</NOBR></P><A NAME="71736"> </A><A NAME="73963"></A>
<P><A NAME="dingp14"></A>
The first construct is the <CODE>bool</CODE> type, which has as its values the keywords <CODE>true</CODE> and <CODE>false</CODE>. If your compilers haven't implemented <CODE>bool</CODE>, there are two ways to approximate it. One is to use a global <NOBR>enum:<SCRIPT>create_link(14);</SCRIPT>
</NOBR></P>
<UL><A NAME="71715"> </A>
<PRE>enum bool { false, true };
</PRE>
</UL>
<A NAME="71748"> </A>
<P><A NAME="dingp15"></A>
This allows you to overload functions on the basis of whether they take a <CODE>bool</CODE> or an <CODE>int</CODE>, but it has the disadvantage that the built-in comparison operators (i.e., <CODE>==</CODE>, <CODE><</CODE>, <CODE>>=</CODE>, etc.) still return <CODE>int</CODE>s. As a result, code like the following will not behave the way it's supposed <NOBR>to:<SCRIPT>create_link(15);</SCRIPT>
</NOBR></P>
<UL><A NAME="71758"> </A>
<PRE>void f(int);
void f(bool);
</PRE><A NAME="71759"> </A>
<PRE>int x, y;
...
f( x < y ); // calls f(int), but it
// should call f(bool)
</PRE>
</UL>
<A NAME="71716"> </A>
<P><A NAME="dingp16"></A>
The enum approximation may thus lead to code whose behavior changes when you submit it to a compiler that truly supports <CODE>bool</CODE>.<SCRIPT>create_link(16);</SCRIPT>
</P><A NAME="71788"> </A>
<P><A NAME="dingp17"></A>
<A NAME="73966"></A><A NAME="73967"></A><A NAME="p4"></A>An alternative is to use a typedef for <CODE>bool</CODE> and constant objects for <CODE>true</CODE> and <CODE>false</CODE>:<SCRIPT>create_link(17);</SCRIPT>
</P>
<UL><A NAME="71795"> </A>
<PRE>typedef int bool;
</PRE><A NAME="71796"> </A>
<PRE>const bool false = 0;
const bool true = 1;
</PRE>
</UL>
<A NAME="71797"> </A>
<P><A NAME="dingp18"></A>
This is compatible with the traditional semantics of C and C++, and the behavior of programs using this approximation won't change when they're ported to <CODE>bool</CODE>-supporting compilers. The drawback is that you can't differentiate between <CODE>bool</CODE> and <CODE>int</CODE> when overloading functions. Both approximations are reasonable. Choose the one that best fits your <NOBR>circumstances.<SCRIPT>create_link(18);</SCRIPT>
</NOBR></P><A NAME="71881"> </A>
<P><A NAME="dingp19"></A>
The second new construct is really four constructs, the casting forms <CODE>static_cast</CODE>, <CODE>const_cast</CODE>, <CODE>dynamic_cast</CODE>, and <CODE>reinterpret_cast</CODE>. If you're not familiar with these casts, you'll want to turn to <A HREF="./MC1_FR.HTM#77216" TARGET="_top">Item 2</A> and read all about them. Not only do they do more than the C-style casts they replace, they do it better. I use these new casting forms whenever I need to perform a cast in this <NOBR>book.<SCRIPT>create_link(19);</SCRIPT>
</NOBR></P><A NAME="74524"> </A>
<P><A NAME="dingp20"></A>
There is more to C++ than the language itself. There is also the standard library (see <A HREF="../EC/EC7_FR.HTM#8392" TARGET="_top">Item E49</A>). <A NAME="74525"></A>Where possible, I employ the standard <CODE>string</CODE> type instead of using raw <CODE>char*</CODE> pointers, and I encourage you to do the same. <CODE>string</CODE> objects are no more difficult to manipulate than <CODE>char*</CODE>-based strings, and they relieve you of most memory-management concerns. Furthermore, <CODE>string</CODE> objects are less susceptible to memory leaks if an exception is thrown (see Items <A HREF="./MC3_FR.HTM#5292" TARGET="_top">9</A> and <A HREF="./MC3_FR.HTM#38223" TARGET="_top">10</A>). A well-implemented <CODE>string</CODE> type can hold its own in an efficiency contest with its <CODE>char*</CODE> equivalent, and it may even do better. (For insight into how this could be, see <A HREF="./MC5_FR.HTM#6073" TARGET="_top">Item 29</A>.) If you don't have access to an implementation of the standard <CODE>string</CODE> type, you almost certainly have access to <I>some</I> <CODE>string</CODE>-like class. Use it. Just about anything is preferable to raw <CODE>char*</CODE>s.<SCRIPT>create_link(20);</SCRIPT>
</P><A NAME="72473"> </A>
<A NAME="74732"></A>
<P><A NAME="dingp21"></A>
I use data structures from the standard library whenever I can. Such data structures are drawn from the Standard Template Library (the "STL" — see <A HREF="./MC6_FR.HTM#5473" TARGET="_top">Item 35</A>). The STL includes bitsets, vectors, lists, queues, stacks, maps, sets, and more, and you should prefer these standardized data structures to the ad hoc equivalents you might otherwise be tempted to write. Your compilers may not have the STL bundled in, but don't let that keep you from using it. Thanks to Silicon Graphics, you can download a free copy that works with many compilers from the <NOBR><FONT COLOR="#FF0000" SIZE="-2"><B>°</B></FONT><A HREF="http://www.awl.com/cseng/cgi-bin/cdquery.pl?name=stltutorial" onMouseOver="self.status='STL Tutorial and Reference Guide'; return true" onMouseOut="self.status=self.defaultStatus" target="_top">SGI</NOBR> STL web site</A>.<SCRIPT>create_link(21);</SCRIPT>
</P><A NAME="72646"> </A>
<P><A NAME="dingp22"></A>
<A NAME="p5"></A>If you currently use a library of algorithms and data structures and are happy with it, there's no need to switch to the STL just because it's "standard." However, if you have a choice between using an STL component or writing your own code from scratch, you should lean toward using the STL. <A NAME="74750"></A>Remember code reuse? STL (and the rest of the standard library) has lots of code that is very much worth <NOBR>reusing.<SCRIPT>create_link(22);</SCRIPT>
</NOBR></p>
<A NAME="71709"> </A><A NAME="74760"></A>
<P><A NAME="dingp23"></A><font ID="mhtitle">Conventions and Terminology</font><SCRIPT>create_link(23);</SCRIPT>
</P>
<A NAME="72706"> </A>
<A NAME="74722"></A>
<P><A NAME="dingp24"></A>
Any time I mention inheritance in this book, I mean public inheritance (see <A HREF="../EC/EC6_FR.HTM#6914" TARGET="_top">Item E35</A>). If I don't mean public inheritance, I'll say so explicitly. When drawing inheritance hierarchies, I depict base-derived relationships by drawing arrows from derived classes to base classes. For example, here is a hierarchy from <A HREF="./MC5_FR.HTM#34883" TARGET="_top">Item 31</A>:<SCRIPT>create_link(24);</SCRIPT>
</P><BR>
<A NAME="73989"></A><A NAME="73990"></A><A NAME="74752"></A>
<SPAN ID="Image1of1" STYLE="position: absolute; z-index:1; visibility: hidden"><IMG SRC="./IMAGES/GRAPHICS/DIAGRAMS/I_005a1.GIF" BORDER=0></SPAN>
<SPAN ID="Image1of2" STYLE="position: absolute; z-index:1; visibility: hidden"><IMG SRC="./IMAGES/GRAPHICS/DIAGRAMS/I_005a2.GIF" BORDER=0></SPAN>
<SPAN ID="Image1of3" STYLE="position: absolute; z-index:1; visibility: hidden"><IMG SRC="./IMAGES/GRAPHICS/DIAGRAMS/I_005a3.GIF" BORDER=0></SPAN>
<SPAN ID="Image1of4" STYLE="position: absolute; z-index:1; visibility: hidden"><IMG SRC="./IMAGES/GRAPHICS/DIAGRAMS/I_005a4.GIF" BORDER=0></SPAN>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -