This is not a problem, just a question that I want to be answered.
I'm making 2D application that has particles. In the click handler I've written this code:
Particle *tempp = new Particle();
tempp->setPosition(mx, my);
particles.push_back(tempp); // typeof particles = std::list<Particle*>
delete tempp; // <- this line is the problem
When I click, one particle will be created at the mouse position. After about one second it should disappears, which works fine. After it's disappeared I can click again to create a new particle.
However, when I click while there still is one particle on the screen, my program freezes and stops working.
My destructor of the Particle class and it's parent's destructor are both empty.
WITHOUT calling delete my program runs fine, even with multiple particles at once, or even multiple per frame. I am just wondering what is causing this freezing issue.
Based on the posted code, the particles container will contain dangling pointers. Any attempt to dereference these is undefined behaviour. I am assuming they are later being used, otherwise the storage of them seems pointless.
Calling push_back() does not copy the pointed-to-object but copies the value of the pointer (the memory address of the dynamically allocated object). If Particle is cheap to copy, is copyable and polymorphic behaviour is unrequired just store the Particle in the container. Otherwise, suggest using a smart pointer, such as std::unique_ptr, to automatically destruct the Particle when removed from the container.
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