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()
?
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).
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 .
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(); };
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.
Your list is of pointers. Pointers don't have destructors. If you want the destructor to be called you should try list<test>
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With