lightburst
lightburst

Reputation: 231

freeing std::list member

I have a list defined as such std::list<BunnyInfo> bList;, private, inside a class where BunnyInfo is a structure

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

where the list grows via member function

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);
    }
}

where fill() is just a function that generates values for the structure. I also have a member function that deletes half the list

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);
    }
}

My question is, how would I delete the list member and at the same time free the resources allocated via add(). delete &(*iter); produces an error, I think, since without it the program runs okay. But simply calling erase() doesn't free the BunnyInfo associated with the list node.

I'm new to using the STL.

Upvotes: 1

Views: 418

Answers (1)

ibid
ibid

Reputation: 3902

Since the list is declared std::list<BunnyInfo>, its insert makes a copy of the object being inserted, and erase automatically disposes of the copy. You thus need not and cannot use delete on that copy.

Since your add alloctes with new an object which it does not delete (and does not store in any data structure), there is a memory leak in add.

If you want to store pointers in the list, you need to declare the list as std::list<BunnyInfo *>.

Upvotes: 5

Related Questions