erasing element of list whle iterating

The list I have contains list of dynamic object

typedef	std::list<MyClass*> ace_list_type;
ace_list_type obj; // List of Dynamically allocated object 

for (ace_list_type::iterator it = obj.begin(); it != obj.end();)
     if (some_condition)  {
	    delete (*it);         // Free's the Memory
	    it = obj.erase(it); // Remove from list 
     } else {

Open in new window

Am I leaking here or creating infinite loop ?
Who is Participating?
jkrConnect With a Mentor Commented:
No, all is fine. As a side note, this e.g. would not work with a vector, because the 'erase()' would invalidate the iterator, but with a list, everything is fine. Also, try to avoid storing poinbters in containers, but I assume you have a good reason to do that.
perlperlAuthor Commented:
Thanks. I agree but its some legacy code. As longs as memory is freed it should be fine ;) to store pointers in containers.
perlperlAuthor Commented:
Jkr, you never responded to my earlier Q. I need to close that Q but now sure which of your comments corresponds to my last comment ;)
>> As longs as memory is freed it should be fine

Agreed. Yet that's the risk - when more than one developer works on such code, chances are that misunderstandings happen. In general, that approach is harder to maintain. But sometimes, it's hard to do things differently...
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.