The same considerations that make move semantics appropriate for constructors make them appropriate for assignment. Here, for example, is how you could code the copy assignment and the move assignment operators for the Useless
class:
Useless & Useless::operator=(const Useless & f) // copy assignment
{
if (this == &f)
return *this;
delete [] pc;
n = f.n;
pc = new char[n];
for (int i = 0; i < n; i++)
pc[i] = f.pc[i];
return *this;
}
Useless & Useless::operator=(Useless && f) // move assignment
{
if (this == &f)
return *this;
delete [] pc;
n = f.n;
pc = f.pc;
f.n = 0;
f.pc = nullptr;
return *this;
}
The copy assignment operator follows the usual pattern given in Chapter 12. The move assignment operator deletes the original data in the target and pilfers the source object. It’s important that only one pointer points to the data, so the method resets the pointer in the source object to the null pointer.
As with the move constructor, the move assignment operator parameter is not a const
reference because the method alters the source object.
18.190.217.253