2

I'm coding an event handling system ( following observer pattern... ) and I'd like to know which is the best way to propagate or spread an Event class, something like this:

class Event{
public:
    Event(int code);
    virtual ~Event();
    int getCode() const;

private:
    int code;
};

In detail if better to send it through a pointer (heap allocated) or as an instance (stack allocated).

Event e(1);
notifyAll(e);

vs

Event * e = new Event(1);
notifyAll(e)

I know it's a really common question, and i know the suggested guidelines for generic cases,but i would like to know in the specific case of event handling taking care of performance, optimization, being thread safe and so on.

My idea is to send through stack allocation, seen that the class is just a POD, and to avoid life managing issues ( or using smart pointers ). On the other side the event propagation tree could be really big in my apps, so I'm afraid it could be an issue.

Thank you. (For instance if you are aware of any good implementation, not as complicated as in qt, to learn from please write it down)

jalone
  • 1,953
  • 4
  • 27
  • 46

1 Answers1

1

If you pass a stack-allocated object by reference, there is no performance difference between that and passing by pointer.

If you pass by pointer, then some piece of code has to be responsible for delete-ing the object. OTOH, if the lifetime of the object needs to persist beyond the scope in which it's created, then you're forced to do dynamic allocation. In that case, perhaps you might need to do reference-counting. It's hard to say without more information.

Paul J. Lucas
  • 6,895
  • 6
  • 44
  • 88
  • thanks for the answer, I'll gather infos about using references, but it should be ok, being the class immutable. – jalone Apr 19 '11 at 18:40