赋值操作符内存泄漏
Memory leak in assignment operator
在我的程序中,我必须重载=操作符。重载函数如下:
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;
}
相关文章:
- C++功能泄漏内存,我是C++新手,不确定如何解决
- 我的堆栈弹出式磁带的实现是否泄漏内存?
- 将 c++ 向量转换为字符 ** 而不会泄漏内存
- 析构函数 C++ 使泄漏内存
- 构造函数对象赋值是否泄漏内存
- corba :: orb_init泄漏内存
- Gmock泄漏内存
- 如何在不泄漏内存的情况下删除链接列表
- Visual C ODBC关闭记录集泄漏内存
- 为什么泄漏内存比在动态数组上执行 delete[] 慢
- OpenGL正在泄漏内存.哪个对象未释放
- 可以std ::退出泄漏内存
- uiautomation findall泄漏内存
- 为什么在此OpenCL代码中泄漏内存,为什么要泄漏内存
- pthread在完成后会泄漏内存
- win32 标准::线程泄漏内存
- 返回指向同一变量的指针是否会泄漏内存
- 使用clectType(new any_type())可能会泄漏内存泄漏
- Windows开发:如何确定我的应用程序是否正在泄漏内存
- WinHttp打开泄漏内存