繁体   English   中英

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

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

我正在阅读“Scott Meyers的有效C ++”,其中第11项建议在我的赋值运算符中使用“复制和交换”技术:

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

但在第12项中写道:

让复制赋值运算符调用复制构造函数是没有意义的。

我认为第11项和第12项是矛盾的。 我不正确地理解它吗?

在Scott Meyers的“Effective C ++”的两个引用中,你提到了两个不同的方面。

  • 在第11项中的代码片段中,Scott显示了实现赋值运算符的方法之一。
  • 在第12项中,您提到的引用涉及避免赋值运算符和复制构造函数之间的代码重复。 引文上方的一段说:

两个复制函数通常具有相似的主体,这可能会诱使您尝试通过让一个函数调用另一个函数来避免代码重复。

我对第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;
}

我反其道而行之。 我重载赋值运算符以执行“深度”复制(意味着您考虑动态内存并相应地实例化新副本)。 然后在复制构造函数中使用赋值运算符。 无法评论您的文字,因为我没有那本书。

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