Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ event system - using heap or stack based events

I'm trying to design a simple event system that, "basically", looks like this:

  • the observer entity keeps a list of all objects that need to be notified. It also stores a queue of fired events. Events are then processed by the object list, iteratint through this object list.
  • an object keeps a list of observers it sends events to. Each particular object, that inherits from the base object, can fire its own specialised events (key, mouse, collision, etc.). The object also has a method HandleEvent(..) with different overloads for compile time type detection, instead of using dynamic_casting.

What would be better to choose, when firing events: creating them on the stack and passing them by reference, or allocating them dynamically on the heap and use dynamic_casting and let the observer deallocate them when they're processed by the objects that can handle them? (e.g. isn't dynamic allocation unnecessary when an event can be fired quite often; what about dynamic casting, isn't it avoidable?).

Also, this is not quite a thread-safe scenario..

like image 375
teodron Avatar asked Aug 03 '26 04:08

teodron


1 Answers

Do you need dynamic allocation? No. Typically, you want

void fireEvent()
{
    Event ev;
    for ( each observer )
       observer.trigger(ev);
}

And the observer's signature

void trigger(const Event& ev);

Note that "passing references to them" isn't true, pedantically speaking. It's actually "passing them by reference".

like image 175
Luchian Grigore Avatar answered Aug 04 '26 19:08

Luchian Grigore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!