在我的程序中,我必须重载 = 运算符。重载函数如下所示:
Polygon &Polygon::operator=(const Polygon &source)
{
this->capacity = source.capacity;
this->index = source.index;
this->vertex = new Vertex[source.capacity];
for(int i = 0; i < source.capacity; i++)
{
this->vertex[i] = source.vertex[i];
}
return *this;
}
但如果我学到了一件事,那就是我有责任删除我用“new”关键字创建的东西。
所以在返回之前我尝试了:
delete vertex;
但这没有用,因为它删除了我刚刚复制到的对象。 所以我尝试了:
delete source.vertex;
这让我的程序在运行时崩溃了。
我也尝试过很多其他的方法,但都是经过深思熟虑的尝试。 我真的很想得到你的帮助,不仅告诉我应该写什么,还告诉我在这些情况下应该如何思考。
最佳答案
在这条语句之前
this->vertex = new Vertex[source.capacity];
插入语句
delete [] this->vertex;
运算符(operator)也必须看下面的方式
Polygon &Polygon::operator=(const Polygon &source)
{
if ( this != &source )
{
this->capacity = source.capacity;
//...
}
return *this;
}
关于c++ - 赋值运算符中的内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22563820/