delete pointers?

the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
EnterCriticalSection(&user_critical);

list <_USERIN_LIST*>::iterator	Iter;

for(Iter = m_UserList.begin(); Iter != m_UserList.end(); Iter++)
{
	if(*Iter)//<--is there any point in doing this?
	{
		if((*Iter)->UserIndex == Index)	break;
	}
}

if(Iter != m_UserList.end())
{
	Iter = m_UserList.erase(Iter);//<--done correctly?
	delete Iter;
}

LeaveCriticalSection(&user_critical);


would my code above be safe and efficient enough to delete a pointer ?
Last edited on
Yes, line 7 is ncessary because the data type _USERIN_LIST* accepts null values (null pointers). If the current item is a null pointer, line 9 would crash and burn.

Line 16 is a mistake because Iter is not a pointer type and you didn't allocate it with operator new. NEVER delete what you didn't new'ed.

It is safe as long as you ALWAYS enter that critical section EVERY TIME you access the list m_UserList for ANYTHING.
1
2
3
4
5
6
7
8
9
10
11
for(Iter = m_UserList.begin(); Iter != m_UserList.end(); Iter++)
{
	if(*Iter)
	{
		if((*Iter)->UserIndex == Index)	break;
	}
	else
	{
		Iter = m_UserList.erase(Iter);
	}
}


another example, would this be safe even though im increasing Iter in the loop whilst also erasing in the same loop?
So now you want to erase null pointers from the collection. Is that it? Anyway, if you do that, the iterator will invalidate. If you do that, you MUST exit the for() loop immediately after the erase operation.
Topic archived. No new replies allowed.