我正在阅读“Scott的有效C++”,其中第11项建议在我的赋值操作符中使用“复制和交换”技术:
Widget& Widget::operator=(const Widget &rhs)
{
Widget temp(rhs); // Copy constructor
swap(temp); //Swap with *this
return *this;
}但在第12项中写着:
让复制赋值操作符调用复制构造函数是没有意义的。
我认为项目11和项目12是相互矛盾的。我是不是理解错了?
发布于 2016-08-08 20:12:20
在你提到的“Scott的有效C++”的两个引用中,讨论了两个不同的方面。
这两个复制函数通常具有相似的主体,这可能会引诱您尝试通过一个函数调用另一个函数来避免代码重复。
我对第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;
}发布于 2016-08-08 16:48:02
我做的正好相反。我重载赋值操作符以执行“深度”复制(这意味着您考虑动态内存并相应地实例化新副本)。然后在复制构造函数中使用赋值操作符。不能评论你的文字,因为我没有那本书。
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;
}https://stackoverflow.com/questions/38834277
复制相似问题