Reputation: 157
I am writing some code for a class project. One of the tasks is to delete a collection of pointers to a class we have created. The solution looks like this:
CDocument::~CDocument()
{
for(std::list<CActor*>::iterator it = mActors.begin(); it != mActors.end(); it++)
{
delete *it;
}
mActors.clear();
}
My solution looked like this:
CDocument::~CDocument()
{
for(std::list<CActor*>::iterator it = mActors.begin(); it != mActors.end(); it++)
{
delete **it;
}
}
My confusion stems from dereferencing the iterator. I want to delete the CActor objects from the list. The iterator provides me, in this case, with a pointer to a pointer. Why would I delete the CActor pointer, *it, rather than the actual object in memory, **it? Also, why the additional mActors.clear()?
Upvotes: 2
Views: 408
Reputation: 13526
Because delete
operates on pointers, not the object itself or a reference to the object.. For example with the code
int* a = new int;
you would delete a
with
delete a;
not
delete *a;
As for why mActors.clear();
is there, it's not strictly necessary since the std::list
destructor will automatically do the same thing. However if more code is ever added to the destructor, clearing the list ensures all those dangling pointers cannot be accidentally used later.
Upvotes: 3