我正在阅读这篇文章Why do we need to delete allocated memory in C++ assignment operator?,我对赋值运算符中由新操作分配的内存有个疑问。在分配给MyString对象testObject之后它将如何释放? testObject的析构函数在超出范围时会被调用,否则我将不得不显式调用delete来释放内存?释放由赋值运算符分配的内存C++
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
}
它应该在析构函数中释放,如果你已经正确实现它。 – juanchopanza 2013-04-24 22:12:29
不完全是重复的,但你需要了解所有关于[Rule of Three](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-ree)如果你打算编写一个资源管理类。 – 2013-04-24 22:14:00
是的,我知道,但是析构函数会释放赋值运算符中分配的内存吗?我认为它只会释放拷贝构造函数中分配的内存。 – vkaul11 2013-04-24 22:15:41