简体   繁体   English

复制和交换技术在赋值运算符函数中使用复制构造函数

[英]copy and swap technique uses copy constructor inside assignment operator function

I was reading "Effective C++ by Scott Meyers", in which Item 11 is recommending is to use the "copy and swap" technique inside my assignment operator: 我正在阅读“Scott Meyers的有效C ++”,其中第11项建议在我的赋值运算符中使用“复制和交换”技术:

Widget& Widget::operator=(const Widget &rhs)
{
    Widget temp(rhs); // Copy constructor
    swap(temp); //Swap with *this
    return *this;
}

But in Item 12 it is written: 但在第12项中写道:

It makes no sense to have copy assignment operator call the copy constructor. 让复制赋值运算符调用复制构造函数是没有意义的。

I think that Item 11 and Item 12 are contradictory. 我认为第11项和第12项是矛盾的。 Am I understanding it incorrectly? 我不正确地理解它吗?

In the 2 citations of "Effective C++ by Scott Meyers" that you mention the 2 different aspects are discussed. 在Scott Meyers的“Effective C ++”的两个引用中,你提到了两个不同的方面。

  • In the code fragment in Item 11 Scott shows one of the ways to implement the assignment operator. 在第11项中的代码片段中,Scott显示了实现赋值运算符的方法之一。
  • In Item 12 the citation you mention deals with avoiding code duplication between the assignment operator and copy constructor. 在第12项中,您提到的引用涉及避免赋值运算符和复制构造函数之间的代码重复。 One paragraph above your citation says: 引文上方的一段说:

the two copying functions will often have similar bodies, and this may tempt you to try to avoid code duplication by having one function call the other. 两个复制函数通常具有相似的主体,这可能会诱使您尝试通过让一个函数调用另一个函数来避免代码重复。

My understanding of this part of Item 12 is like this: if you try to write something like below (to have copy assignment operator call the copy constructor) then it will be wrong: 我对第12项的这一部分的理解是这样的:如果你尝试写下面的东西(让复制赋值操作符调用复制构造函数)那么它将是错误的:

PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs)
: Customer(rhs),   // invoke base class copy ctor
  priority(rhs.priority)
{
  logCall("PriorityCustomer copy constructor");
}

PriorityCustomer&
PriorityCustomer::operator=(const PriorityCustomer& rhs)
{
  logCall("PriorityCustomer copy assignment operator");
  this->PriorityCustomer(rhs); // This line is wrong!!!
  return *this;
}

I do the opposite. 我反其道而行之。 I overload the assignment operator to do a "deep" copy (meaning you consider dynamic memory and instantiate new copies accordingly). 我重载赋值运算符以执行“深度”复制(意味着您考虑动态内存并相应地实例化新副本)。 Then use the assignment operator in copy constructor. 然后在复制构造函数中使用赋值运算符。 Can't comment on your text because I don't have that book. 无法评论您的文字,因为我没有那本书。

Widget::Widget(const Widget& existing) : dynamicThingie(0)
{
    *this = existing;
}


Widget& Widget::operator=(const Widget& existing)
{
    a = existing.a;
    b = existing.b;

    delete dynamicThingie;
    dynamicThingie = new Thingie();
    memcpy(dynamicThingie, existing.dynamicThingie, lengthOfDynamicThingue);

    return *this;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM