use*_*670 2 c++ memory-leaks operator-keyword
在我的程序中,我必须重载 = 运算符。重载函数如下所示:
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;
}
Run Code Online (Sandbox Code Playgroud)
但如果我学到了一件事,那就是我负责删除我用“new”关键字创建的东西。
所以在回来之前我尝试过:
delete vertex;
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为它删除了我刚刚复制到的对象。所以我尝试了:
delete source.vertex;
Run Code Online (Sandbox Code Playgroud)
这使我的程序在运行时崩溃了。
我也尝试过很多其他的方法,但它们只是有想法的尝试。我真的很希望你的帮助,不仅告诉我应该写什么,还告诉我在这些情况下应该如何思考。
在此声明之前
this->vertex = new Vertex[source.capacity];
Run Code Online (Sandbox Code Playgroud)
插入语句
delete [] this->vertex;
Run Code Online (Sandbox Code Playgroud)
操作员还必须按以下方式查看
Polygon &Polygon::operator=(const Polygon &source)
{
if ( this != &source )
{
this->capacity = source.capacity;
//...
}
return *this;
}
Run Code Online (Sandbox Code Playgroud)