c++ - Memory Deallocating freezes my program -


this not problem, question want answered.

i'm making 2d application has particles. in click handler i've written code:

particle *tempp = new particle(); tempp->setposition(mx, my); particles.push_back(tempp); // typeof particles = std::list<particle*> delete tempp; // <- line problem 

when click, 1 particle created @ mouse position. after 1 second should disappears, works fine. after it's disappeared can click again create new particle.

however, when click while there still 1 particle on screen, program freezes , stops working.

my destructor of particle class , it's parent's destructor both empty.

without calling delete program runs fine, multiple particles @ once, or multiple per frame. wondering causing freezing issue.

based on posted code, particles container contain dangling pointers. attempt dereference these undefined behaviour. assuming later being used, otherwise storage of them seems pointless.

calling push_back() not copy pointed-to-object copies value of pointer (the memory address of dynamically allocated object). if particle cheap copy, copyable , polymorphic behaviour unrequired store particle in container. otherwise, suggest using smart pointer, such std::unique_ptr, automatically destruct particle when removed container.


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -