无法使用 delete 释放分配的内存

Couldn't free allocated memory using delete

我正在如下成员函数中分配内存:

void Wrapper::PutData() {

mpeople.append(new people("ALPHA","BEETA","GAMMA", this));
mpeople.append(new people("ALPHA","BEETA","GAMMA", this));
mpeople.append(new people("ALPHA","BEETA","GAMMA", this));

}

其中 mpeople 对象被声明为

QList<QObject*> mpeople;

一切正常,直到我尝试使用以下成员函数删除项目

void Wrapper::RemoveClient(int index){
    if(index >= 0){
        delete[] mpeople[index];
        mpeople.removeAt(index);
    }
    resetModel();
}

您正在尝试对未使用标量新建分配的对象执行标量删除。那是delete,不是delete [].

只需这样做:

void Wrapper::RemoveClient(int index){
    if(index >= 0){
        delete mpeople[index];
        mpeople.removeAt(index);
    }
    resetModel();
}

一种更现代的方式,是使用shared_ptr或unique_ptr或等效的qt智能指针class。

这样声明:

QList<std::shared_ptr<QObject>> mpeople;

这样插入:

mpeople.append(std::make_shared<people>("ALPHA","BEETA","GAMMA", this));

像这样删除:

mpeople.removeAt(index); // pointer will get deleted for you when the last reference goes away