c++ - 赋值运算符中的内存泄漏

标签 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;
}

但如果我学到了一件事,那就是我有责任删除我用“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/

相关文章:

C++ typedef union 编译错误

c++ - 大写函数在 Visual Studio 2013 (C++) 上不起作用

c++ - 由于内存不足导致linux应用程序崩溃

c# - 在 C# 中显式释放内存

C++ 没有运算符 ">>"匹配这些操作数(<string> 包含在 header 中)

c++ - Boost 程序选项允许输入值集

c++ - 空 vector 是其结构的大小吗?

Python 内存泄漏 - 已解决,但仍然感到困惑

c++ - const 转换运算符的行为

java - 我一直收到 "The operator == is undefined for the argument type(s) boolean, int"并且不知道如何修复它