C++ 析构函数抛出错误

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[] 表达式创建的。例如

// 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 (list(a pointer)+x) 这不是释放你创建的内存...... 您正在尝试通过在其中添加 x 循环的值来删除列表旁边的地址 我希望你理解你的错误 :)