STL question: Is it necessary to delete an object from std::list
I have a question regarding to STL std::list objects.
Let we have a definition of own structure:
Code:
struct MYSTRUCT
{
std::string strFile;
DWORD dwSize;
BOOL bFlag;
};
Then we create some global std:list object:
std::list<MYSTRUCT*> g_MyStructList;
Also we have a function to add objects into that list:
Code:
void AddObject(LPSTR lpstrFile, DWORD dwSize, BOOL bFlag)
{
MYSTRUCT* pMySrtuct = new MYSTRUCT;
pMySrtuct->strFile = lpstrFile;
pMySrtuct->dwSize = dwSize;
pMySrtuct->bFlag = bFlag;
g_MyStructList.push_front(pMySrtuct);
}
My question is simple and regards to removing the objects from the list:
Code:
void RemoveObjects()
{
std::list<MYSTRUCT*>::iterator itr = g_MyStructList.begin();
while(itr != g_MyStructList.end())
{
delete *itr; // is it necessary to delete the iterator or may be g_MyStructList.remove will do that?
g_MyStructList.remove(*itr);
itr = g_MyStructList.begin();
itr++;
}
}
The question is:
Does g_MyStructList.remove will only remove the object from the list or it also will free the memory dinamically allocated for MYSTRUCT object in AddObject function?
Also if the answer is NO (it does not delete the object, it just removes the object from the list and we must delete the iterator ourself), what should be the first: removing from the list or delete?
Code:
delete *itr;
g_MyStructList.remove(*itr);
or
g_MyStructList.remove(*itr);
delete *itr;
Thank you for the answers.
Re: STL question: Is it necessary to delete an object from std::list
Quote:
Originally posted by Miran
Then we create some global std:list object:
std::list<MYSTRUCT*> g_MyStructList;
...
Also we have a function to add objects into that list:
Your code does not store objects in the list -- it stores pointers in the list, not objects.
This code below stores objects. There is also no need for delete if you stored objects. So to answer your question, you do not "delete" objects from the list, unless the "object" is a pointer to dynamically allocated memory. The simple rule is this -- if you call "new", then you are responsible for calling "delete". If you didn't call "new", then you don't call "delete".
Code:
#include <list>
std::list<MYSTRUCT> g_MyStructList;
//...
int main()
{
MYSTRUCT m;
g_MyStructList.push_back( m );
// No need for delete
}
Also, there is no way for the container to call delete if you did store pointers. The container has no knowledge that you placed dynamically allocated pointers in the container. You could have easily have done this:
Code:
#include <list>
std::list<MYSTRUCT *> g_MyStructList;
//...
int main()
{
MYSTRUCT m;
g_MyStructList.push_back(&m );
//...
}
If the container were to call "delete", it would be incorrect, since the pointer is an address of a non-dynamically allocated MYSTRUCT.
Regards,
Paul McKenzie