Sign in to follow this  

sd::list and pointers how to delete?

This topic is 2544 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
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

This topic is 2544 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this