[英]C++ destructor throws error
我有以下代码:
class MyList
{
private:
public:
int* list;
int size = 0;
int max;
// constructor
MyList(int s)
{
max = s;
size = 0;
if(max > 0)
list = new int[max];
};
// destructor
~MyList()
{
for (int x = 0; x < max; x++)
delete (list + x);
};
};
我试图用该析构函数清除内存。 但是,它在第二次迭代时引发错误。 我做错了什么? 另外,它不会让我这样:
delete list[x];
有人可以向我解释原因吗? 非常感谢。
您应该使用delete[]
因为list
是通过new[]
-expression创建的。 例如
// destructor
~MyList()
{
delete[] list;
}
请注意,它们必须成对。 new int[max]
创建一个包含max
元素的数组, delete[]
破坏整个数组。 delete
应该仅用于由new
创建的指针。
最好将构造函数更改为
// constructor
MyList(int s)
{
max = s;
size = 0;
if(max > 0)
list = new int[max];
else
list = nullptr;
}
确保list
始终有效。
尝试这个:
MyList(int s)
: max(s),
size(0),
list(new int[s])
{
};
~MyList()
{
delete[] list;
};
我不明白你为什么要使用循环来释放该内存....你应该简单的写
delete []列表;
那就足够了! 在析构函数中,您使用的是delete(列表(指针)+ x),这不是在释放创建的内存...您正在尝试通过添加x循环的值来删除列表旁边的地址,希望您理解您的错误:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.