I'm having a problem with a couple of event handler classes I'm trying to write. Basically, the idea is to have an event handler class for each logical group of objects. In most cases, the events are between objects and their handler, but in some cases events are also sent between handler objects as well.
I've written the code such that the events are placed on a stack (stack as in user created structure; the events themselves are allocated using new
) and delete
d after their information is read and acted upon. This is giving me some problems because in one case, the event is sent along a chain of three handlers. Say, HandlerA
sends a new Event
to HandlerB
, which places it on the stack and reads it, sending it to HandlerC
, which reads it and performs whatever it needs to perform, after which it delete
s the Event pointer and sets it to NULL
. Now, we pop back to HandlerB
and, well, it also wants to delete
and NULL
the pointer to the event. But the pointer is a local variable, and it ends up deleting the same address twice, giving an exception.
How do you go around this? Do you need to use one of those fancy auto_ptr
s (still an early learner here), or am I missing something fundamental here?
I've written the code such that the events are placed on a stack and deleted after their information is read and acted upon.
There is some confusion here - objects on the stack should not be delete
d. Objects created with new
(on the heap) should.
In general, you should define a clear ownership strategy for your objects on the heap. Each object should have one owner, and it should be clear who the owner is at any point in time. That owner - and it alone - shall delete
the object.
You may also want to use boost::shared_ptr
(it may be available also as std::tr1::shared_ptr
, depending on your compiler) instead of raw pointers. This keeps count of the references to the object, and delete
s it when the ref count drops to 0.