赋值操作符内存泄漏

Memory leak in assignment operator

本文关键字:泄漏 内存 赋值操作符      更新时间:2023-10-16

在我的程序中,我必须重载=操作符。重载函数如下:

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];

insert语句

delete [] this->vertex;

操作符也必须按照如下方式

Polygon &Polygon::operator=(const Polygon &source)
{
    if ( this != &source )
    {
       this->capacity = source.capacity;
       //...
    }
    return *this;
}

程序可能崩溃,因为您使用delete删除了用operator new[](而不是operator new)创建的指针。这是两码事。您总是需要匹配这两个,使用delete[]new[]:

int *p = new int;
delete p;
int *q = new int[10];
delete [] q;

不能删除顶点,因为对象还在引用它。Polygon的析构函数应该负责删除它创建的Vertex对象:

~Polygon::Polygon()
{
    if (vertex)
        delete[] vertex;
}