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

📄 ei16.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>Effective C++, 2E | Item 16: Assign to all data members in operator=</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 = "EI16_DIR.HTM";
var dingtext = "Item E16, P";
if (self == top) {
 top.location.replace(dingbase + this.location.hash);
}
</SCRIPT>

</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" ONLOAD="setResize()">
<!-- SectionName="E16: Assign to all data members in operator=" -->
<A NAME="2225"></A>
<DIV ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="./EI15_FR.HTM" TARGET="_top">Item 15: Have operator= return a reference to *this.</A> &nbsp;&nbsp;<BR>&nbsp;&nbsp;Continue to <A HREF="./EI17_FR.HTM" TARGET="_top">Item 17: Check for assignment to self in operator=. </A></FONT></DIV>

<P><A NAME="dingp1"></A><A NAME="p68"></A><FONT ID="eititle">Item 16: &nbsp;Assign to all data members in <CODE>operator=</CODE>.</FONT><SCRIPT>create_link(1);</SCRIPT>
</P><A NAME="2226"></A>
<P><A NAME="dingp2"></A>
<A HREF="./EI45_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="./EI11_FR.HTM#2042" TARGET="_top">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(2);</SCRIPT>
</NOBR></P>
<A NAME="2227"></A>
<P><A NAME="dingp3"></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(3);</SCRIPT>
</NOBR></P>
<A NAME="15759"></A>
<UL><PRE>
template&lt;class T&gt;          // template for classes associating
class NamedPtr {           // names with pointers (from <A HREF="./EI12_FR.HTM#2071" TARGET="_top">Item 12</A>)
public:
  NamedPtr(const string&amp; initName, T *initPtr);
  NamedPtr&amp; operator=(const NamedPtr&amp; rhs);
</PRE>
</UL><A NAME="15972"></A>
<UL><PRE>private:
  string name;
  T *ptr;
};
</PRE>
</UL><A NAME="2228"></A>
<UL><PRE>template&lt;class T&gt;
NamedPtr&lt;T&gt;&amp; NamedPtr&lt;T&gt;::operator=(const NamedPtr&lt;T&gt;&amp; rhs)
{
  if (this == &amp;rhs)
    return *this;              // see <A HREF="./EI17_FR.HTM#2264" TARGET="_top">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="./EI15_FR.HTM#2182" TARGET="_top">Item 15</A>
}
</PRE>
</UL><A NAME="2236"></A>
<P><A NAME="dingp4"></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(4);</SCRIPT>
</NOBR></P>
<A NAME="2237"></A>
<P><A NAME="dingp5"></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(5);</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&amp; operator=(const Derived&amp; rhs);
</PRE>
</UL><A NAME="15986"></A>
<UL><PRE>private:
  int y;
};
</PRE>
</UL><A NAME="2243"></A>
<P><A NAME="dingp6"></A>
The logical way to write <CODE>Derived</CODE>'s assignment operator is like <NOBR>this:<SCRIPT>create_link(6);</SCRIPT>
</NOBR></P>
<A NAME="2244"></A>
<UL><PRE>// erroneous assignment operator
Derived&amp; Derived::operator=(const Derived&amp; rhs)
{
  if (this == &amp;rhs) return *this;    // see <A HREF="./EI17_FR.HTM#2264" TARGET="_top">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><PRE>
  return *this;                      // see <A HREF="./EI15_FR.HTM#2182" TARGET="_top">Item 15</A>
}
</PRE>
</UL><A NAME="31710"></A>
<P><A NAME="dingp7"></A>
Unfortunately, this is incorrect, because the data member <CODE>x</CODE> in the <CODE>Base</CODE> part of a <CODE>Derived</CODE> object is unaffected by this assignment operator. For example, consider this code fragment:<SCRIPT>create_link(7);</SCRIPT>

<A NAME="31711"></A>
<UL><PRE>void assignmentTester()
{
  Derived d1(0);                      // d1.x = 0, d1.y = 0
  Derived d2(1);                      // d2.x = 1, d2.y = 1
</PRE>
</UL><A NAME="2249"></A>
<UL><PRE>  d1 = d2;			      // d1.x = 0, d1.y = 1!
}
</PRE>
</UL><A NAME="2250"></A>
<P><A NAME="dingp8"></A>
Notice how the <CODE>Base</CODE> part of <CODE>d1</CODE> is unchanged by the <NOBR>assignment.<SCRIPT>create_link(8);</SCRIPT>
</NOBR></P>
<A NAME="2251"></A>
<P><A NAME="dingp9"></A>
The straightforward way to fix this problem would be to make an assignment to <CODE>x</CODE> in <CODE>Derived::operator=</CODE>. Unfortunately, that's not legal, because <CODE>x</CODE> is a private member of <CODE>Base</CODE>. Instead, you have to make <A NAME="p70"></A>an explicit assignment to the <CODE>Base</CODE> <I>part</I> of <CODE>Derived</CODE> from inside <CODE>Derived</CODE>'s assignment <NOBR>operator.<SCRIPT>create_link(9);</SCRIPT>
</NOBR></P>
<A NAME="2257"></A>
<P><A NAME="dingp10"></A>
This is how you do it:<SCRIPT>create_link(10);</SCRIPT>


<A NAME="15871"></A>
<UL><PRE>// correct assignment operator
Derived&amp; Derived::operator=(const Derived&amp; rhs)
{
  if (this == &amp;rhs) return *this;
</PRE>
</UL><A NAME="15872"></A>
<UL><PRE>  Base::operator=(rhs);    // call this-&gt;Base::operator=
  y = rhs.y;
</PRE>
</UL><A NAME="15873"></A>
<UL><PRE>  return *this;
}
</PRE>
</UL><A NAME="15874"></A>
<P><A NAME="dingp11"></A>
Here you just make an explicit call to <CODE>Base::operator=</CODE>. That call, like all calls to member functions from within other member functions, will use <CODE>*this</CODE> as its implicit left-hand object. The result will be that <CODE>Base::operator=</CODE> will do whatever work it does on the <CODE>Base</CODE> part of <CODE>*this</CODE> &#151; precisely the effect you <NOBR>want.<SCRIPT>create_link(11);</SCRIPT>
</NOBR></P>
<A NAME="15878"></A>
<P><A NAME="dingp12"></A>
Alas, some compilers (incorrectly) reject this kind of call to a base class's assignment operator if that assignment operator was generated by the compiler (see <A HREF="./EI45_FR.HTM#8160" TARGET="_top">Item 45</A>). To pacify these renegade translators, you need to implement <CODE>Derived::operator=</CODE> this <NOBR>way:<SCRIPT>create_link(12);</SCRIPT>
</NOBR></P>
<A NAME="15893"></A>
<UL><PRE>Derived&amp; Derived::operator=(const Derived&amp; rhs)
{
  if (this == &amp;rhs) return *this;
</PRE>
</UL><A NAME="15899"></A>
<UL><PRE>
  static_cast&lt;Base&amp;&gt;(*this) = rhs;      // call operator= on
                                        // Base part of *this
  y = rhs.y;
</PRE>
</UL><A NAME="15887"></A>
<UL><PRE>  return *this;
}
</PRE>
</UL><A NAME="2261"></A>
<P><A NAME="dingp13"></A>
This monstrosity casts <CODE>*this</CODE> to be a reference to a <CODE>Base</CODE>, then makes an assignment to the result of the cast. That makes an assignment to only the <CODE>Base</CODE> part of the <CODE>Derived</CODE> object. Careful now! It is important that the cast be to a <I>reference</I> to a <CODE>Base</CODE> object, not to a <CODE>Base</CODE> object itself. If you cast <CODE>*this</CODE> to be a <CODE>Base</CODE> object, you'll end up calling the copy constructor for <CODE>Base</CODE>, and the new object you construct (see <A HREF="../MEC/MI19_FR.HTM#41177" TARGET="_top">Item M19</A>) will be the target of the assignment; <CODE>*this</CODE> will remain unchanged. Hardly what you <NOBR>want.<SCRIPT>create_link(13);</SCRIPT>
</NOBR></P>
<A NAME="140795"></A>
<P><A NAME="dingp14"></A>
Regardless of which of these approaches you employ, once you've assigned the <CODE>Base</CODE> part of the <CODE>Derived</CODE> object, you then continue with <CODE>Derived</CODE>'s assignment operator, making assignments to all the data members of <CODE>Derived</CODE>.<SCRIPT>create_link(14);</SCRIPT>
</P>
<A NAME="140798"></A>
<P><A NAME="dingp15"></A>
<A NAME="p71"></A>A similar inheritance-related problem often arises when implementing derived class copy constructors. Take a look at the following, which is the copy constructor analogue of the code we just <NOBR>examined:<SCRIPT>create_link(15);</SCRIPT>
</NOBR></P>
<A NAME="15917"></A>
<UL><PRE>class Base {
public:
  Base(int initialValue = 0): x(initialValue) {}
  Base(const Base&amp; rhs): x(rhs.x) {}
</PRE>
</UL><A NAME="15993"></A>
<UL><PRE>private:
  int x;
};
</PRE>
</UL><A NAME="15919"></A>
<UL><PRE>class Derived: public Base {
public:
  Derived(int initialValue)
  :  Base(initialValue), y(initialValue) {}
</PRE>
</UL><A NAME="15932"></A>
<UL><PRE>
  Derived(const Derived&amp; rhs)      // erroneous copy
  : y(rhs.y) {}                    // constructor
</PRE>
</UL><A NAME="15999"></A>
<UL><PRE>private:
  int y;
};
</PRE>
</UL><A NAME="15931"></A>
<P><A NAME="dingp16"></A>
Class <CODE>Derived</CODE> demonstrates one of the nastiest bugs in all C++-dom: it fails to copy the base class part when a <CODE>Derived</CODE> object is copy constructed. Of course, the <CODE>Base</CODE> part of such a <CODE>Derived</CODE> object is constructed, but it's constructed using <CODE>Base</CODE>'s <I>default</I> constructor. Its member <CODE>x</CODE> is initialized to 0 (the default constructor's default parameter value), regardless of the value of <CODE>x</CODE> in the object being <NOBR>copied!<SCRIPT>create_link(16);</SCRIPT>
</NOBR></P>
<A NAME="15954"></A>
<P><A NAME="dingp17"></A>
To avoid this problem, <CODE>Derived</CODE>'s copy constructor must make sure that <CODE>Base</CODE>'s copy constructor is invoked instead of <CODE>Base</CODE>'s default constructor. That's easily done. Just be sure to specify an initializer value for <CODE>Base</CODE> in the member initialization list of <CODE>Derived</CODE>'s copy <NOBR>constructor:<SCRIPT>create_link(17);</SCRIPT>
</NOBR></P>
<A NAME="15957"></A>
<UL><PRE>class Derived: public Base {
public:
  Derived(const Derived&amp; rhs): Base(rhs), y(rhs.y) {}
</PRE>
</UL><A NAME="15960"></A>
<UL><PRE>  ...
</PRE>
</UL><A NAME="16010"></A>
<UL><PRE>};
</PRE>
</UL><A NAME="15955"></A>
<P><A NAME="dingp18"></A>
Now when a client creates a <CODE>Derived</CODE> by copying an existing object of that type, its <CODE>Base</CODE> part will be copied, <NOBR>too.<SCRIPT>create_link(18);</SCRIPT>
</NOBR></P>

<DIV ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="./EI15_FR.HTM" TARGET="_top">Item 15: Have operator= return a reference to *this.</A> &nbsp;&nbsp;<BR>&nbsp;&nbsp;Continue to <A HREF="./EI17_FR.HTM" TARGET="_top">Item 17: Check for assignment to self in operator=. </A></FONT></DIV>

</BODY>
</HTML>

⌨️ 快捷键说明

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