📄 ec3.htm
字号:
</UL><A NAME="31136"></A>
<P><A NAME="dingp87"></A>
The usual motivation is to prevent clients from doing silly things like <NOBR>this:<SCRIPT>create_link(87);</SCRIPT>
</NOBR></P>
<A NAME="219527"></A>
<UL><PRE><A NAME="p66"></A>Widget w1, w2, w3;
</PRE>
</UL><A NAME="219531"></A>
<UL><PRE>...
</PRE>
</UL><A NAME="219532"></A>
<UL><PRE>
(w1 = w2) = w3; // assign w2 to w1, then w3 to
// the result! (Giving Widget's
// operator= a const return value
// prevents this from compiling.)
</PRE>
</UL><A NAME="31140"></A>
<P><A NAME="dingp88"></A>
Silly this may be, but not so silly that it's prohibited for the built-in <NOBR>types:<SCRIPT>create_link(88);</SCRIPT>
</NOBR></P>
<A NAME="31143"></A>
<UL><PRE>int i1, i2, i3;
</PRE>
</UL><A NAME="31144"></A>
<UL><PRE>...
</PRE>
</UL><A NAME="31145"></A>
<UL><PRE>
(i1 = i2) = i3; // legal! assigns i2 to
// i1, then i3 to i1!
</PRE>
</UL><A NAME="2203"></A>
<P><A NAME="dingp89"></A>
I know of no practical use for this kind of thing, but if it's good enough for the <CODE>int</CODE>s, it's good enough for me and my classes. It should be good enough for you and yours, too. Why introduce gratuitous incompatibilities with the conventions followed by the built-in <NOBR>types?<SCRIPT>create_link(89);</SCRIPT>
</NOBR></P>
<A NAME="31164"></A>
<P><A NAME="dingp90"></A>
Within an assignment operator bearing the default signature, there are two obvious candidates for the object to be returned: the object on the left hand side of the assignment (the one pointed to by <CODE>this</CODE>) and the object on the right-hand side (the one named in the parameter list). Which is <NOBR>correct?<SCRIPT>create_link(90);</SCRIPT>
</NOBR></P>
<A NAME="2204"></A>
<P><A NAME="dingp91"></A>
Here are the possibilities for a <CODE>String</CODE> class (a class for which you'd definitely want to write an assignment operator, as explained in <A HREF="#2042">Item 11</A>):<SCRIPT>create_link(91);</SCRIPT>
</P>
<A NAME="2205"></A>
<UL><PRE>String& String::operator=(const String& rhs)
{
</PRE>
</UL><A NAME="2206"></A>
<UL><PRE> ...
</PRE>
</UL><A NAME="2207"></A>
<UL><PRE>
return *this; // return reference
// to left-hand object
}
</PRE>
</UL><A NAME="2208"></A>
<UL><PRE>String& String::operator=(const String& rhs)
{
</PRE>
</UL><A NAME="2209"></A>
<UL><PRE> ...
</PRE>
</UL><A NAME="2210"></A>
<UL><PRE>
return rhs; // return reference to
// right-hand object
}
</PRE>
</UL><A NAME="2211"></A>
<P><A NAME="dingp92"></A>
This might strike you as a case of six of one versus a half a dozen of the other, but there are important <NOBR>differences.<SCRIPT>create_link(92);</SCRIPT>
</NOBR></P>
<A NAME="2212"></A>
<P><A NAME="dingp93"></A>
<A NAME="p67"></A>First, the version returning <CODE>rhs</CODE> won't compile. That's because <CODE>rhs</CODE> is a reference-to-<CODE><I>const</I></CODE>-<CODE>String</CODE>, but <CODE>operator=</CODE> returns a reference-to-<CODE>String</CODE>. Compilers will give you no end of grief for trying to return a reference-to-non-<CODE>const</CODE> when the object itself is <CODE>const</CODE>. That seems easy enough to get around, however — just redeclare <CODE>operator=</CODE> like <NOBR>this:<SCRIPT>create_link(93);</SCRIPT>
</NOBR></P>
<A NAME="2213"></A>
<UL><PRE>String& String::operator=(String& rhs) { ... }
</PRE>
</UL><A NAME="2214"></A>
<P><A NAME="dingp94"></A>
Alas, now the client code won't compile! Look again at the last part of the original chain of <NOBR>assignments:<SCRIPT>create_link(94);</SCRIPT>
</NOBR></P>
<A NAME="2216"></A>
<UL><PRE>x = "Hello"; // same as x.op=("Hello");
</PRE>
</UL><A NAME="2217"></A>
<P><A NAME="dingp95"></A>
Because the right-hand argument of the assignment is not of the correct type — it's a <CODE>char</CODE> array, not a <CODE>String</CODE> — compilers would have to create a temporary <CODE>String</CODE> object (via the <CODE>String</CODE> constructor — see <A HREF="../MEC/MC4_FR.HTM#41177" TARGET="_top">Item M19</A>) to make the call succeed. That is, they'd have to generate code roughly equivalent to <NOBR>this:<SCRIPT>create_link(95);</SCRIPT>
</NOBR></P>
<A NAME="2218"></A>
<UL><PRE>const String temp("Hello"); // create temporary
</PRE>
</UL><A NAME="2219"></A>
<UL><PRE>x = temp; // pass temporary to op=
</PRE>
</UL><A NAME="15466"></A>
<P><A NAME="dingp96"></A>
Compilers are willing to create such a temporary (unless the needed constructor is <CODE>explicit</CODE> — see <A HREF="./EC4_FR.HTM#5887" TARGET="_top">Item 19</A>), but note that the temporary object is <CODE>const</CODE>. This is important, because it prevents you from accidentally passing a temporary into a function that modifies its parameter. If that were allowed, programmers would be surprised to find that only the compiler-generated temporary was modified, not the argument they actually provided at the call site. (We know this for a fact, because early versions of C++ allowed these kinds of temporaries to be generated, passed, and modified, and the result was a lot of surprised <NOBR>programmers.)<SCRIPT>create_link(96);</SCRIPT>
</NOBR></P>
<A NAME="15467"></A>
<P><A NAME="dingp97"></A>
Now we can see why the client code above won't compile if <CODE>String</CODE>'s <CODE>operator=</CODE> is declared to take a reference-to-non-<CODE>const</CODE> <CODE>String</CODE>: it's never legal to pass a <CODE>const</CODE> object to a function that fails to declare the corresponding parameter <CODE>const</CODE>. That's just simple <CODE>const</CODE>-correctness.<SCRIPT>create_link(97);</SCRIPT>
</P>
<A NAME="2224"></A>
<P><A NAME="dingp98"></A>
You thus find yourself in the happy circumstance of having no choice whatsoever: you'll always want to define your assignment operators in such a way that they return a reference to their left-hand argument, <CODE>*this</CODE>. If you do anything else, you prevent chains of assignments, you prevent implicit type conversions at call sites, or <NOBR>both.<SCRIPT>create_link(98);</SCRIPT>
</NOBR></P>
<!-- SectionName="E16: Assign to all data members in operator=" -->
<A NAME="2225"></A><A NAME="p68"></A><DIV ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="#2182">Item 15: Have operator= return a reference to *this.</A>
<BR>Continue to <A HREF="#2264">Item 17: Check for assignment to self in operator=.</A></FONT></DIV>
<P><A NAME="dingp99"></A><FONT ID="eititle">Item 16: Assign to all data members in <CODE>operator=</CODE>.</FONT><SCRIPT>create_link(99);</SCRIPT>
</P><A NAME="2226"></A>
<P><A NAME="dingp100"></A>
<A HREF="./EC7_FR.HTM#8160" TARGET="_top">Item 45</A> explains that C++ will write an assignment operator for you if you don't declare one yourself, and <A HREF="#2042">Item 11</A> describes why you often won't much care for the one it writes for you, so perhaps you're wondering if you can somehow have the best of both worlds, whereby you let C++ generate a default assignment operator and you selectively override those parts you don't like. No such luck. If you want to take control of any part of the assignment process, you must do the entire thing <NOBR>yourself.<SCRIPT>create_link(100);</SCRIPT>
</NOBR></P>
<A NAME="2227"></A>
<P><A NAME="dingp101"></A>
In practice, this means that you need to assign to <I>every</I> data member of your object when you write your assignment <NOBR>operator(s):<SCRIPT>create_link(101);</SCRIPT>
</NOBR></P>
<A NAME="15759"></A>
<UL><PRE>
template<class T> // template for classes associating
class NamedPtr { // names with pointers (from <A HREF="#2071">Item 12</A>)
public:
NamedPtr(const string& initName, T *initPtr);
NamedPtr& operator=(const NamedPtr& rhs);
</PRE>
</UL><A NAME="15972"></A>
<UL><PRE>private:
string name;
T *ptr;
};
</PRE>
</UL><A NAME="2228"></A>
<UL><PRE>template<class T>
NamedPtr<T>& NamedPtr<T>::operator=(const NamedPtr<T>& rhs)
{
if (this == &rhs)
return *this; // see <A HREF="#2264">Item 17</A>
</PRE>
</UL><A NAME="2234"></A>
<UL><PRE> // assign to all data members
name = rhs.name; // assign to name
</PRE>
</UL><A NAME="15826"></A>
<UL><PRE>
*ptr = *rhs.ptr; // for ptr, assign what's
// pointed to, not the
// pointer itself
</PRE>
</UL><A NAME="2235"></A>
<UL><PRE>
return *this; // see <A HREF="#2182">Item 15</A>
}
</PRE>
</UL><A NAME="2236"></A>
<P><A NAME="dingp102"></A>
This is easy enough to remember when the class is originally written, but it's equally important that the assignment operator(s) be updated if new data members are added to the class. For example, if you decide to upgrade the <CODE>NamedPtr</CODE> template to carry a timestamp marking when the name was last changed, you'll have to add a new data member, and this will require updating the constructor(s) as well as the assignment operator(s). In the hustle and bustle of upgrading a class and adding new member functions, etc., it's easy to let this kind of thing slip your <NOBR>mind.<SCRIPT>create_link(102);</SCRIPT>
</NOBR></P>
<A NAME="2237"></A>
<P><A NAME="dingp103"></A>
<A NAME="p69"></A>The real fun begins when inheritance joins the party, because a derived class's assignment operator(s) must also handle assignment of its base class members! Consider <NOBR>this:<SCRIPT>create_link(103);</SCRIPT>
</NOBR></P>
<A NAME="2238"></A>
<UL><PRE>class Base {
public:
Base(int initialValue = 0): x(initialValue) {}
</PRE>
</UL><A NAME="15979"></A>
<UL><PRE>private:
int x;
};
</PRE>
</UL><A NAME="2240"></A>
<UL><PRE>class Derived: public Base {
public:
Derived(int initialValue)
: Base(initialValue), y(initialValue) {}
</PRE>
</UL><A NAME="2242"></A>
<UL><PRE> Derived& operator=(const Derived& rhs);
</PRE>
</UL><A NAME="15986"></A>
<UL><PRE>private:
int y;
};
</PRE>
</UL><A NAME="2243"></A>
<P><A NAME="dingp104"></A>
The logical way to write <CODE>Derived</CODE>'s assignment operator is like <NOBR>this:<SCRIPT>create_link(104);</SCRIPT>
</NOBR></P>
<A NAME="2244"></A>
<UL><PRE>// erroneous assignment operator
Derived& Derived::operator=(const Derived& rhs)
{
if (this == &rhs) return *this; // see <A HREF="#2264">Item 17</A>
</PRE>
</UL><A NAME="2245"></A>
<UL><PRE>
y = rhs.y; // assign to Derived's
// lone data member
</PRE>
</UL><A NAME="2246"></A>
<UL><PR
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -