Possible Duplicate:
Does std::list::remove method call destructor of each removed element?
Assume I have this:
void f(...)
{
.
.
std::list<X*> xList;
.
// Then i fill the list
std::list<X*>::iterator iter;
for (iter = xList.begin(); iter != xList.end(); ++iter)
{
*iter = new X();
}
}
When xList goes out of scope, I know that the container should call the destructor of the objects that are contained within the list? First, is that true?
If so, then since the list contains pointers to class X shouldn't the destructor ofX be called when xList goes out of scope? Thus freeing any memory that was held by X?
Yes and no.
Each elements' destructor will be called.
However this won't result in the effect you want. The elements are of type X*
, thus the destructor of X*
will be called (which does nothing for pointer type) rather than destructor of X that you need. You need to explicitly delete your elements. In general, if you have new
in your code, there should be a corresponding delete
.