Jump to content
  • Advertisement
Sign in to follow this  
MARS_999

sd::list and pointers how to delete?

This topic is 2736 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am bit fuzzy on the correct way to delete pointers in a std::list with a remove() also is my destructor correct?

I think I need to call delete *it; in the remove(), but how do I erase that element in the std::list then?


std::list<NX::OBJECT::Object*> objects;
std::list<NX::OBJECT::Object*>::iterator it;

~Factory()
{
for(it = objects.begin(); it != objects.end(); ++it)
if(*it)
delete *it;
objects.clear();
}

inline void Insert(NX::OBJECT::Object* obj)
{
objects.push_back(obj);
}
inline void Remove(const std::string& id)
{
for(it = objects.begin(); it != objects.end(); ++it)
if((*it)->GetName() == id)
{
objects.erase(it);
break;
}
}




Share this post


Link to post
Share on other sites
Advertisement
The correct way is to use a smart pointer and not worry about it. Otherwise in your Remove() function you need to call delete *it before you erase the iterator.

Share this post


Link to post
Share on other sites
Thanks for the tip SiCrane...

Here is my updated code. I thought about it a bit more makes sense but never hurts to ask then hunt bugs down later.


inline void Remove(const std::string& id)
{
for(it = objects.begin(); it != objects.end(); ++it)
if((*it)->GetName() == id)
{
if(*it)
delete *it;
objects.erase(it);
break;
}
}

Share this post


Link to post
Share on other sites
Calling delete on a null pointer is a no-op. Checking for a null before you delete it is doubly silly in your loop because if the pointer was null, it'd have already crashed your program during the GetName() call.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!