简体   繁体   中英

Deleting objects within a list with shared_ptr

My goal here is to delete a projectile whenever it hits something. I have a function in the projectile class that returns a boolean value of the state of the projectile (is to delete or not). The problem is that I don't know when and where I should delete it.

In my project, I'm creating a projectile and adding it in 2 different classes with a std::list. The first class (let's say it is in ProjectileGestion) contains all the projectiles and updates them each frame before sending them to a DrawGestion (The DrawGestion will put every sprite in order of y and draw them). The second class is a Quadtree that contains a list of all the objects within is perimeter (Each frame, it checks if each object in his list still fit in and will check for collisions). For the moment, I don't delete any projectile, since I don't know how. I thought of 2 options:

  1. Only the ProjectileGestion can delete the projectile. Whenever it deletes an object, it deletes the object and changes the value of the pointer to NULL. In the other class Quadtree, when I cycle through the list with iterators, I check if each iterator is equal to NULL. If it is, the class will erase the iterator from the list and continue on.

     std::list<Object*>::iterator i = listOfObjects.begin(); while(i != listOfObjects.end()) { //Update() if((*i)->IsToDelete()) { delete *i; *i = NULL; listOfObjects.erase(i++); } else { i++; } } 

2: I use a std::shared_ptr when declaring the object.I do the same check up as I did in option 1, but I only erase the object from the list, I don't actually delete the object. That way, when every list will have erased the object from it, the object will be deleted. (Note that I never used smart pointers before).

So which way is more efficient and is less prone to cause a memory leak?

They should be about the same efficiency since std::unique_ptr will use template code that will add similar code to what you wrote. However, using std::unique_ptr will be less error prone if you ever change that code or add other code that deals with the pointers.

More importantly, the unique_ptr code makes your intentions more explicit and makes the code easier to read and maintain. You can tell by looking at the declaration that it's a list of exclusively owned objects and your erase becomes 1 line.

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