I was checking assignment operator implementations, and I do not understand this:
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
}
Why can't I just do this instead, without freeing memory then allocating new memory?
void operator=(const MyString& rhs)
{
if (this != &rhs) {
strcpy(this->str, rhs.str); // copy characters
this->length = rhs.length; // copy length
}
}
Why can't I just update the values in the existing memory?