1

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?

Community
  • 1
  • 1
Kam
  • 5,878
  • 10
  • 53
  • 97
  • This is not relevant to your immediate questions, but this is not a fill operation. It's an assignment to the elements of the list. In the case that the list remained empty from its creation on, it's also a no-op. – Luc Danton Oct 21 '12 at 16:40

2 Answers2

3

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.

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85
  • Thank you so much! Ok a silly question can the destructor of X* be somehow overloaded? – Kam Oct 21 '12 at 16:44
  • @Kam No, and you don't want to do that either. –  Oct 21 '12 at 16:46
  • @Kam, Smart pointers will ensure your object's destructors are called when the smart pointer's is. – chris Oct 21 '12 at 16:52
  • @chris, Thank you, yes I know, and actually that's what I do now, I only wanted to understand the behavior. I just somehow wrongly assumed I guess that the desctructor of a pointer to an object will call the destructor of that object. – Kam Oct 21 '12 at 16:53
1

In C++ standard library design a container is the only owner of the contained elements so when the container is destroyed all elements are destroyed.

However note that "destroying" a naked pointer in C++ is a no-operation so the pointed-to element will not be deleted (a naked pointer may point to statically allocated data or to data that is owned by some other container).

What you can do is creating either an std::list of the elements (instead of pointer to the elements) or (in case you need a pointer because of, for example, polymorphism) you can instead use smart pointers that can take care of the pointed elements if you like so.

6502
  • 112,025
  • 15
  • 165
  • 265