stl list erase w/ new

Started by
10 comments, last by Gink 18 years, 9 months ago
I have created an stl list to store student* I add a student like this: students.push_back(new Student(nextStuId, name, grade, zip)); so I need to delete the students when I am done. If I delete a student in the list using erase do I need to call delete or will it take care of it? Also to delete everything when I am done should I do something like this?

	for(studentsIter = students.begin(); studentsIter != students.end(); studentsIter++)
	{
		delete *studentsIter;
	}

Advertisement
You need to call delete, erase will just remove the pointer from the list.
If I delete it will it be there for me to erase or will it be gone?
if u are using a list the corect form is:

for(studentsIter = students.begin(); studentsIter != students.end(); studentsIter++)
{
delete studentsIter;//<- you delete the object not the pointer
}
If you have an STL list of plain pointers, then you have to delete the memory manually, the STL will not do it for you. When you call erase, it just removes the pointer from the list, not the data it points to.

Use a smart pointer like boost::shared_ptr. It will automatically delete what it points to when it is destroyed.

www.boost.org

This way, you don't have to worry about accidently forgetting to delete something, etc.
Quote:Original post by Grahf750
If I delete it will it be there for me to erase or will it be gone?


The pointer is still there (even if it points to deleted memory) waiting for you to erase it. What you are doing is simply removing that element from the list. It could have anything (or nothing) in that element and the stl list won't care. So delete the pointer then erase the element from the list and you're golden.
yeah or auto_ptr works
Quote:Original post by Gink
yeah or auto_ptr works

No it doesn't. auto_ptr doesn't have the correct copy semantics for use in STL containers. A standards-compatible compiler will refuse to allow it.
Quote:Original post by Gink
yeah or auto_ptr works


No it doesn't, you can't store auto_ptr in an STL container, because it transfers ownership when it is copied. Use boost::shared_ptr instead, it's reference counted.

Edit: Beaten
Lol

Quote:It will automatically delete what it points to when it is destroyed.


I meant it automatically deletes the object it refers to when it's destroyed as well

This topic is closed to new replies.

Advertisement