I was going through this post Why do we need to delete allocated memory in C++ assignment operator? and I had a question about the memory allocated by new operation inside the assignment operator. How will it be freed after we assign to a MyString object testObject? Will the destructor for the testObject be called when it goes out of scope or I will have to call delete explicitly to free that memory?
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
}