Why do we need the delete statement?
const MyString& operator=(const MyString& rhs)
{
if (this != &rhs) {
delete[] this->str; // Why is this required?
this->str = new char[strlen(rhs.str) + 1]; // allocate new memory
strcpy(this->str, rhs.str); // copy characters
this->length = rhs.length; // copy length
}
return *this; // return self-reference so cascaded assignment works
}
This is not a copy constructor, it’s the assignment operator. You need the
delete[]because the object being assigned is holding already a previous value.This code is also not really good because first deletes the old value and then allocates the new one… but the allocation may throw an exception and in this case the object will keep a pointer to a deallocated area. A better approach is first allocate and then delete the old value (an exception should never be allowed to escape from a destructor… see this link for an explanation) so either the assignment succeeds or fails without compromising anything.
A common idiom is to implement a copy constructor and a swap operation (that swaps the contents of two instances guaranteeing that no exception will be thrown). Then you implement the assignment operator combining the two… this requires both less code and is robust from an exception handling point of view.