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:
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:
It makes no sense to have copy assignment operator call the copy constructor.
I think that Item 11 and Item 12 are contradictory. Am I understanding it incorrectly?
In the 2 citations of "Effective C++ by Scott Meyers" that you mention the 2 different aspects are discussed.
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:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With