Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 413
danikaze Avatar asked Sep 30 '12 22:09

danikaze


People also ask

Does clear call destructor C++?

std::vector<T>::clear() always calls the destructor of each element, but the destructor of a pointer is a no-op (or a pointer has a trivial destructor).

Does C automatically call destructors?

A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete .

How are destructors called in C++?

A destructor is called for a class object when that object passes out of scope or is explicitly deleted. A destructor is a member function with the same name as its class prefixed by a ~ (tilde). For example: class X { public: // Constructor for class X X(); // Destructor for class X ~X(); };

What happens when destructor is not called?

There are two reasons that your destructors aren't being called, one is as kishor8dm pointed out that you are using the operator "new" and because of that the "delete" command must be called explicitly.


1 Answers

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

like image 178
CrazyCasta Avatar answered Sep 18 '22 15:09

CrazyCasta