小编use*_*670的帖子

赋值运算符中的内存泄漏

在我的程序中,我必须重载 = 运算符。重载函数如下所示:

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)

这使我的程序在运行时崩溃了。

我也尝试过很多其他的方法,但它们只是有想法的尝试。我真的很希望你的帮助,不仅告诉我应该写什么,还告诉我在这些情况下应该如何思考。

c++ memory-leaks operator-keyword

2
推荐指数
1
解决办法
316
查看次数

标签 统计

c++ ×1

memory-leaks ×1

operator-keyword ×1