正在释放std::list成员

freeing std::list member

本文关键字:list 成员 std 释放      更新时间:2023-10-16

BunnyInfo是结构的类中,我有一个定义为std::list<BunnyInfo> bList;、private的列表

struct BunnyList::BunnyInfo {
    std::string name;
    char gender;
    std::string color;
    unsigned int age : 6; // 0 - 63
    bool mutant;
};

其中列表通过成员函数增长

void BunnyList::add(int count){
    bListIter iter;
    while(count--){
        BunnyInfo *bNew = &fill(*new BunnyInfo());
        for(iter = bList.begin(); iter != bList.end(); iter++){
            if(iter->age <= bNew->age)
                break;
        }
        bList.insert(iter, *bNew);
    }
}

其中CCD_ 3只是为结构生成值的函数。我还有一个成员功能,可以删除列表的一半

void BunnyList::reap(){
    int toKill = bList.size() / 2;
    int find;
    bListIter iter;
    while(toKill--){
        find = rng(0, bList.size()-1);
        iter = bList.begin();
        for(int i = 0; i < find; i++)   // traverse list to the find-th node;
            iter++;
        delete &(*iter);
        bList.erase(iter);
    }
}

我的问题是,如何删除列表成员,同时释放通过add()分配的资源。我认为delete &(*iter);会产生一个错误,因为没有它程序运行正常。但是简单地调用erase()并不能释放与列表节点相关联的BunnyInfo

我是STL的新手。

由于列表被声明为std::list<BunnyInfo>,它的insert会复制插入的对象,而erase会自动处理该副本。因此,您不需要也不能在该副本上使用delete

由于addnew分配了一个它不是delete(并且不存储在任何数据结构中)的对象,因此add中存在内存泄漏。

如果要在列表中存储指针,则需要将列表声明为std::list<BunnyInfo *>