Вопрос

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top