Why does c ++ std :: list :: clear () not call destructors?

Take a 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 list item destructor not called in l.clear() ?

+6
source share
2 answers

On your list of pointers. Pointers do not have destructors. If you want the destructor to be called, you should try list<test> .

+12
source

The best alternative to freeing pointers using delete , or using something that abstracts them (like smart pointers or pointer containers), is to simply create 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 used std::list "real" elements, rather than pointers to elements, you would not have this problem.

+3
source

Source: https://habr.com/ru/post/926631/


All Articles