Original Post
This is something I have never tried before. My game engine is based around events. The main event class of my event system is the EventDispatcher. The EventDispatcher is responsible for making sure all the event subscribers get notified when an event is raised. It has a list of all subscribers, for each event type. I use this data structure: . Then I realized that this wouldn't work because my EventDispatcher is allocated on the stack, but shared_ptr is used to make sure that heap memory gets deallocated, so there'd probably be some runtime crash or assert or something. So then I decided to use naked pointers, that is, EventDispatcher*. This would work fine, but since there should never be a null EventDispatcher and it should never accidentally be deleted, I thought that I could maybe give each class an EventDispatcher& instead, like this:
typedef std::list <EventHandler&> EventHandlerList;
typedef std::map <std::string, EventHandlerList> EventHandlerMap;
It's important that the EventHandlerMap in the EventDispatcher be up do date, so I must use handles to refer to my instance of EventDispatcher (which is usually contained in the Game or Application class). My point is, I can't just have each class who uses to EventDispatcher to raise events have a copy, they must have some kind of handle. Originally I was using boost::shared_ptr. Every class that raised events would have a boost::shared_ptr
class VideoSystem {
private:
const EventDispatcher& dispatcher;
public:
VideoSystem(const EventDispatcher& dispatcher) : dispatcher(dispatcher) {
dispatcher.RaiseEvent(VideoSystemCreatedEvent());
}
};
class Game {
private:
VideoSystem video;
EventDispatcher dispatcher;
public:
Game() : video(dispatcher) {
// whatever
}
};
So my question is this: Is this okay? I have never seen this before, but I see no reason why it's a bad idea. On the contrary, it seems very elegant but I want to be sure before I commit to this design. Also, if it's not a bad design, why is it so uncommon?