首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >复制和交换技术在赋值操作符函数中使用复制构造函数。

复制和交换技术在赋值操作符函数中使用复制构造函数。
EN

Stack Overflow用户
提问于 2016-08-08 16:29:57
回答 2查看 751关注 0票数 5

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

代码语言:javascript
复制
Widget& Widget::operator=(const Widget &rhs)
{
    Widget temp(rhs); // Copy constructor
    swap(temp); //Swap with *this
    return *this;
}

但在第12项中写着:

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

我认为项目11和项目12是相互矛盾的。我是不是理解错了?

EN

回答 2

Stack Overflow用户

发布于 2016-08-08 20:12:20

在你提到的“Scott的有效C++”的两个引用中,讨论了两个不同的方面。

  • 在条目11中的代码片段中,Scott展示了实现赋值操作符的一种方法。
  • 在第12项中,您提到的引文涉及避免赋值操作符和复制构造函数之间的代码重复。在你的引文上面有一段说:

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

我对第12项这一部分的理解是这样的:如果您试图编写如下内容(让复制赋值操作符调用复制构造函数),那么它将是错误的:

代码语言:javascript
复制
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;
}
票数 3
EN

Stack Overflow用户

发布于 2016-08-08 16:48:02

我做的正好相反。我重载赋值操作符以执行“深度”复制(这意味着您考虑动态内存并相应地实例化新副本)。然后在复制构造函数中使用赋值操作符。不能评论你的文字,因为我没有那本书。

代码语言:javascript
复制
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;
}
票数 -7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38834277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档