📄 mi1.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 1: Distinguish between pointers and references</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 = "MI1_DIR.HTM"; var dingtext = "Item M1, P"; if (self == top) {
top.location.replace(dingbase + this.location.hash);
}</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" ONLOAD="setResize()">
<!-- SectionName="M1: Distinguish between pointers and references" -->
<A NAME="11029"></A>
<DIV ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="./MBASICFR.HTM" TARGET="_top">Basics</A> <BR> Continue to <A HREF="./MI2_FR.HTM" TARGET="_top" onMouseOver = "self.status = 'Link to Item 2'; return true" onMouseOut = "self.status = self.defaultStatus">Item 2: Prefer C++-style casts</A></FONT></DIV>
<P><A NAME="dingp1"></A><font ID="mititle">Item 1: Distinguish between pointers and references.</font><SCRIPT>create_link(1);</SCRIPT>
</P>
<A NAME="72103"></A>
<A NAME="31049"></A>
<P><A NAME="dingp2"></A>
Pointers and references <i>look</i> different enough (pointers use the "<CODE>*</CODE>" and "<CODE>-></CODE>" operators, references use "<CODE>.</CODE>"), but they seem to do similar things. Both pointers and references let you refer to other objects indirectly. How, then, do you decide when to use one and not the <NOBR>other?<SCRIPT>create_link(2);</SCRIPT>
</NOBR></P><A NAME="31050"></A>
<P><A NAME="dingp3"></A>
First, recognize that there is no such thing as a null reference. A reference must <I>always</I> refer to some object. As a result, if you have a variable whose purpose is to refer to another object, but it is possible that there might not be an object to refer to, you should make the variable <A NAME="p10"></A>a pointer, because then you can set it to null. On the other hand, if the variable must <I>always</I> refer to an object, i.e., if your design does not allow for the possibility that the variable is null, you should probably make the variable a <NOBR>reference.<SCRIPT>create_link(3);</SCRIPT>
</NOBR></P><A NAME="65886"></A>
<P><A NAME="dingp4"></A>
"But wait," you wonder, "what about underhandedness like <NOBR>this?"<SCRIPT>create_link(4);</SCRIPT>
</NOBR></P><A NAME="65887"></A>
<UL><PRE>char *pc = 0; // set pointer to null
<A NAME="65888"></A>
char& rc = *pc; // make reference refer to
// dereferenced null pointer</PRE>
</UL>
<A NAME="31095"></A>
<P><A NAME="dingp5"></A>
Well, this is evil, pure and simple. The results are undefined (compilers can generate output to do anything they like), and people who write this kind of code should be shunned until they agree to cease and desist. If you have to worry about things like this in your software, you're probably best off avoiding references entirely. Either that or finding a better class of programmers to work with. We'll henceforth ignore the possibility that a reference can be <NOBR>"null."<SCRIPT>create_link(5);</SCRIPT>
</NOBR></P><A NAME="65889"></A>
<P><A NAME="dingp6"></A>
Because a reference must refer to an object, C++ requires that references be <NOBR>initialized:<SCRIPT>create_link(6);</SCRIPT>
</NOBR></P><A NAME="31102"></A>
<UL><PRE>string& rs; // error! References must
// be initialized
<A NAME="31104"></A>
string s("xyzzy");
<A NAME="31105"></A>
string& rs = s; // okay, rs refers to s</PRE>
</UL>
<A NAME="31106"></A>
<P><A NAME="dingp7"></A>
Pointers are subject to no such <NOBR>restriction:<SCRIPT>create_link(7);</SCRIPT>
</NOBR></P>
<A NAME="31107"></A>
<UL><PRE>string *ps; // uninitialized pointer:
// valid but risky</PRE>
</UL>
<A NAME="65942"></A>
<P><A NAME="dingp8"></A>
The fact that there is no such thing as a null reference implies that it can be more efficient to use references than to use pointers. That's because there's no need to test the validity of a reference before using <NOBR>it:<SCRIPT>create_link(8);</SCRIPT>
</NOBR></P><A NAME="31066"></A>
<UL><PRE>void printDouble(const double& rd)
{
cout << rd; // no need to test rd; it
} // must refer to a double</PRE>
</UL>
<A NAME="31130"></A>
<P><A NAME="dingp9"></A>
Pointers, on the other hand, should generally be tested against <NOBR>null:<SCRIPT>create_link(9);</SCRIPT>
</NOBR></P><A NAME="31085"></A>
<UL><PRE>void printDouble(const double *pd)
{
if (pd) { // check for null pointer
cout << *pd;
}
}</PRE>
</UL>
<A NAME="31064"></A>
<A NAME="p11"></A><P><A NAME="dingp10"></A>
Another important difference between pointers and references is that pointers may be reassigned to refer to different objects. A reference, however, <I>always</I> refers to the object with which it is <NOBR>initialized:<SCRIPT>create_link(10);</SCRIPT>
</NOBR></P><A NAME="31164"></A>
<UL><PRE>string s1("Nancy");
string s2("Clancy");
<A NAME="31165"></A>
string& rs = s1; // rs refers to s1
<A NAME="31167"></A>
string *ps = &s1; // ps points to s1<A NAME="31186"></A>
rs = s2; // rs still refers to s1,
// but s1's value is now
// "Clancy"
<A NAME="31187"></A>
ps = &s2; // ps now points to s2;
// s1 is unchanged</PRE>
</UL>
<A NAME="31199"></A><P><A NAME="dingp11"></A>
In general, you should use a pointer whenever you need to take into account the possibility that there's nothing to refer to (in which case you can set the pointer to null) or whenever you need to be able to refer to different things at different times (in which case you can change where the pointer points). You should use a reference whenever you know there will always be an object to refer to and you also know that once you're referring to that object, you'll never want to refer to anything <NOBR>else.<SCRIPT>create_link(11);</SCRIPT>
</NOBR></P>
<A NAME="31206"></A>
<P><A NAME="dingp12"></A>
There is one other situation in which you should use a reference, and that's when you're implementing certain operators. The most common example is <CODE>operator[]</CODE>. This operator typically needs to return something that can be used as the target of an <NOBR>assignment:<SCRIPT>create_link(12);</SCRIPT>
</NOBR></P><A NAME="31230"></A>
<UL><PRE>vector<int> v(10); // create an int vector of size 10;
// vector is a template in the
// standard C++ library (see <a href="./MI35_FR.HTM#5473" TARGET="_top" onMouseOver = "self.status = 'Link to Item 35'; return true" onMouseOut = "self.status = self.defaultStatus">Item 35</A>)</PRE>
</UL><A NAME="31250"></A>
<UL><PRE>v[5] = 10; // the target of this assignment is
// the return value of operator[]
</PRE>
</UL><A NAME="31257"></A>
<P><A NAME="dingp13"></A>
If <CODE>operator[]</CODE> returned a pointer, this last statement would have to be written this <NOBR>way:<SCRIPT>create_link(13);</SCRIPT>
</NOBR></P><A NAME="31258"></A>
<UL><PRE>*v[5] = 10;
</PRE>
</UL><A NAME="31259"></A>
<P><A NAME="dingp14"></A>
But this makes it look like <CODE>v</CODE> is a vector of pointers, which it's not. For this reason, you'll almost always want <CODE>operator[]</CODE> to return a reference. (For an interesting exception to this rule, see <a href="./MI30_FR.HTM#6074" TARGET="_top" onMouseOver = "self.status = 'Link to Item 30'; return true" onMouseOut = "self.status = self.defaultStatus">Item 30</A>.)<SCRIPT>create_link(14);</SCRIPT>
</P><A NAME="77177"></A>
<P><A NAME="dingp15"></A>
References, then, are the feature of choice when you <i>know</i> you have something to refer to, when you'll <I>never</I> want to refer to anything else, and when implementing operators whose syntactic requirements make the use of pointers undesirable. In all other cases, stick with <NOBR>pointers.<SCRIPT>create_link(15);</SCRIPT>
</NOBR></P>
<DIV ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="./MBASICFR.HTM" TARGET="_top">Basics</A> <BR> Continue to <A HREF="./MI2_FR.HTM" TARGET="_top" onMouseOver = "self.status = 'Link to Item 2'; return true" onMouseOut = "self.status = self.defaultStatus">Item 2: Prefer C++-style casts</A></FONT></DIV>
</BODY>
</HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -