C++ -<Task> 删除堆上分配的任务数组时,将列表 l(或任何 STL 容器)添加为数据成员会导致错误

C++ - Adding a list<Task> l (or any STL Container) as a data member is causing an error, when deleting an array of tasks allocated on heap

本文关键字:STL 容器 任何 错误 列表 数据成员 添加 删除 gt Task lt      更新时间:2023-10-16

我有一个名为Task的类。头文件如下所示:

class Task
{
public:
    Task();
//Methods Declarations
private:
int uid;
list<Task> l;
    friend ostream & operator<<(ostream & os, const Task &t);
    friend ostream & operator<<(ostream & os, const list<Task *> &l);
};

现在在我的主文件中,我运行:

Task * tasks[7];
for (int i = 0; i != 7; ++i)
    tasks[i] = new Task();
delete [] *tasks;

在运行delete[] *tasks;时,我得到以下错误消息:

Assignment 4(23901) malloc: *** error for object 0x1001009f8: pointer being 
                                freed was not allocated *** set a breakpoint in 
                                malloc_error_break to debug

一旦我注释掉list < Task *> l并重新运行它,错误消息就会消失。我尝试将list < Task * > l更改为list < Task > l,但没有成功。

我想不通。当在堆栈上分配list < Task >(指向堆元素的井指针)时,为什么会出错?(STL管理)。也尝试了vector<int>。我得到了同样的东西。

更新:删除任务[i]没有做到这一点。

您不使用

delete [] *tasks;

但是

for (int i = 0; i != 7; ++i)
    delete tasks[i];