danikaze
danikaze

Reputation: 1654

Why is C++ std::list::clear() not calling destructors?

Look at this code:

class test
{
    public:
        test() { cout << "Constructor" << endl; };
        virtual ~test() { cout << "Destructor" << endl; };
};

int main(int argc, char* argv[])
{
    test* t = new test();
    delete(t);
    list<test*> l;
    l.push_back(DNEW test());
    cout << l.size() << endl;
    l.clear();
    cout << l.size() << endl;
}

And then, look at this output:

    Constructor
    Destructor
    Contructor
    1
    0

The question is: Why is the destructor of the list element not called at l.clear()?

Upvotes: 9

Views: 9605

Answers (2)

David Stone
David Stone

Reputation: 28913

A better alternative to freeing pointers using delete, or using something that abstracts that away (such as a smart pointers or pointer containers), is to simply create the objects directly on the stack.

You should prefer test t; over test * t = new test(); You very rarely want to deal with any pointer that owns a resource, smart or otherwise.

If you were to use a std::list of 'real' elements, rather than pointers to elements, you would not have this problem.

Upvotes: 4

CrazyCasta
CrazyCasta

Reputation: 28362

Your list is of pointers. Pointers don't have destructors. If you want the destructor to be called you should try list<test> instead.

Upvotes: 14

Related Questions