user1819636
user1819636

Reputation:

How to delete a STL list of pointers?

I have a a list of pairs. Is it a good idea to iterate over the list and delete the first and the second element? The objects in it are allocated with new.

list<pair<string,GraphObject*>>* table;
for(i=0; i< length; i++){
    it = table[i].begin();
    while(it != table[i].end()){
        delete (*it).second;
        delete &(*it).first;
    }
}

EDIT: string is not allocated with new, I know now I don't have to delete it. Is it okay to delete the second this way?

Upvotes: 1

Views: 1723

Answers (3)

Mark Ransom
Mark Ransom

Reputation: 308392

You can't delete the first part of the pair because it isn't a pointer; your code shouldn't even compile. What you can do is delete the whole table when you're done.

list<pair<string,GraphObject*>>* table;
for(i=0; i< length; i++){
    it = table[i].begin();
    while(it != table[i].end()){
        delete (*it).second;
    }
}
delete table;

As to whether you should delete the GraphObject* second member of the pair, that would depend on whether there are other copies of the pointer that will be deleted elsewhere. Presumably there aren't so your original code is correct. As pointed out in another answer, it would be easier to use a smart pointer instead so you don't have to worry about it.

Upvotes: 0

billz
billz

Reputation: 45420

Looks like you your actual need is std::map with smart pointer

std::map<std::string, std::shared_ptr<GraphObject>> table;

To clear table, you simply write:

table.clear();

If you have to work with std::list, still use smart pointers, you still only need to call table.clear(); to clear whole table.

std::list<std::pair<std::string, std::shared_ptr<GraphObject>>> table;

Upvotes: 5

Steve Jessop
Steve Jessop

Reputation: 279315

The string is not allocated with new, it's a data member of the pair. Your second delete is an error.

Maybe it's a copy of a string object that was allocated with new, but if so then you probably leaked the original long ago.

For the first delete -- it is a good idea to delete objects that were allocated with new, if and only if you don't need them any more. You don't say whether you still need these objects (i.e. whether you still have other pointers to them). However, it's an even better idea to use smart pointers to help manage memory.

Upvotes: 1

Related Questions