简体   繁体   中英

C++: Delete pointers from std::list

Digging through a bunch of headers, I found these across some files:

Objects& objects
typedef ObjectPointers Objects;
typedef std::list<Object*> ObjectPointers;

So, this tells me that objects is really a list of pointers to Object. Is this correct?

I'm getting a memory leak and I think it is because objects is not being freed. Would I delete the pointers in objects , or delete objects entirely? I've tried the following, with none of them working:

for(auto&& child : objects) {
  delete child;
}
----------------------

delete[] objects

----------------------

objects.~Object()

What is the proper way to delete objects , and is my thought process correct about what objects actually is?

EDIT:

After further research, it seems like I need to delete the pointers in objects . So this is what I did:

if (!objects.empty()) {
    Objects::const_iterator it;
    for (it = objects.begin(); it != objects.end(); it++) {
      if (*it) {
        delete *it;  //error here
      }
    }
  }

I'm getting a core and it doesn't like the fact that delete *it is void. If *it was void, wouldn't the loop not run to begin with? Even if it did, I'm checking to see if *it exists before I try to delete it, so it shouldn't get there if it doesn't exist anyways.

Like Some programmer dude mentioned, objects is a reference to a std::list of pointers to Object s.

If you wanted to destroy all the elements of the list you could do so with a simple loop:

#include <list>
#include <iostream>

class Object {
public:
    Object() { std::cout << "Object()\n"; }
    ~Object() { std::cout << "~Object()"; }
};

typedef std::list<Object*> ObjectPointers;
typedef ObjectPointers Objects;

int main()
{
    std::list<Object*> objects_list;
    
    objects_list.push_back(new Object());
    
    for (auto* obj: objects_list) {
        delete obj;
    }
    
    // Clear the elements from the list to avoid "use after free" issues
    objects_list.clear();
}


// This program outputs:
// Object()
// ~Object() 

Note that objects in your code is not a std::list but a reference to one. This means that objects simply "points to" the std::list , but doesn't own it. You must ensure that objects isn't used after the std::list is destroyed to avoid issues.

Another question is: who owns the elements of the std::list that object references? If the std::list itself owns the elements it contains, it may be useful to consider using unique_ptr instead of raw pointers, or even putting directly Object values in the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM