sd::list and pointers how to delete?

Started by
2 comments, last by SiCrane 13 years, 3 months ago
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;    }}
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.
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;			}	}
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.

This topic is closed to new replies.

Advertisement