I was reading one of the recommended C++ book, on copy-assignment section it suggests;
It is cricially important for assignment operator to work correctly, even when object is assigned to itself. A good way to do so is to copy the right-hand operand before destroying the left hand operand.
the example in the book; class has one data member ps
and ps is string *
C& operator=(const C &rhs)
{
auto newp = new string(*rhs.ps)
delete ps;
ps = newp;
return *this;
}
but our instructor suggested
C& operator=(const C &rhs)
{
if (this == &rhs)
return *this;
delete ps;
ps = new string(*rhs.ps)
return *this;
}
is there any problem with the instructors' approach?