views:

136

answers:

3

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 deleted 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 deletes 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_ptrs (still an early learner here), or am I missing something fundamental here?

Thanks.

+10  A: 
Péter Török
I meant on a user-created stack structure, not in the sense you meant. Sorry!
Kristian D'Amato
I think the OP means a stack data structure and not the stack.
Jackson
@Kristian, I see, thanks for your clarification. Then the problem is not as bad as it first seemed :-)
Péter Török
+1 for defining ownership strategy. At any point in time, There Can Be Only One owner for any heap allocation. Smart pointers can help you communicate and enforce this.
Pontus Gagge
Thanks, so back to the drawing boards for me then!
Kristian D'Amato
I have deleted my answer and up-voted yours. You say what I wanted to say, only clearer :)
utnapistim
+6  A: 

What you want is some pointer wrapper that for instances uses reference counting to check if other variables reference the same instance. The idea is, that the object the pointer points to is only deallocated when that object is not used by any other pointer. Those kind of pointers are generally refered to as Smart Pointers. In c++ you can for instance use the ones provided by Boost.

inflagranti
+1  A: 

The problem as I see it is that there is no clear owner of the pointer. One solution will be smart pointers as pointed out in inflagranti's answer. Alternatively you could stop forwarding the event twice - when a handler (Handler B in your example) receives an event that it needs to forward to another handler, it creates a new event rather than passing on the pointer to the existing event.

That said; if you are wiling to spend the time looking into them I think that the Smart Pointer solution is probably better!

Jackson