samedi 1 juillet 2017

How to empty std::set from objects' pointers?

I am having an issue emptying my set, so I have 3 classes like so: class A, and 2 inherited classes B and C. in the code I store elements in my set from the 3 types, the set is: set<A*> objects;

so whenever I create a B element I do that:

A* b = new B(); // calling B C'tor

// and so on with A and C elements I do the exact same.

So here comes the problem, whenever I want to erase an element, or even end the program (which calls the D'tor), I don't know what I should type in the destructor, I have it like that: set<A*>::iterator first = objects.begin(); set<A*>::iterator last = objects.end(); while (first != last) { set<A*>::iterator to_delete = first; objects.erase(to_delete); delete *to_delete;
++first; }

I have also tried putting the delete *to_delete; above objects.erase , also tried putting it alone ,and tried putting the erase alone without delete, but the thing is I have used new so I should use delete somewhere. all things aren't working, the program just crashes with that, I tried keeping the D'tor empty, the program works, but I have a lot of memory leaks, I have checked that.

Please help me, I stuck with this thing. Thank you very much <3

Aucun commentaire:

Enregistrer un commentaire