I have a simple event handling system that is giving me issues. To use it I inherit from the class EventHandler
. The constructor then registers each object on construction.
Here is EventHandler
's constructor:
EventHandler::EventHandler()
{
EventDispatcher::getInstance().registerListener(this);
}
This calls EventDispatcher
's registerListener()
member function which stores this in a vector.
void EventDispatcher::registerListener(EventHandler* listener)
{
mListenerList.push_back(listener);
}
Where is mLisernerList looks like:
vector<EventHandler*> mListenerList;
The EventDispatcher
simply calls the sendEvent()
on each element of the vector to notify it of the event.
Let me give an example to demonstrate my issue. Lets say my class Buttons
inherits from EventHandler
. I will create button objects on the heap and then place smart pointers to all my buttons in a single vector.
vector<unique_ptr<Buttons>> mButtons;
mButtons.push_back(unique_ptr<Buttons>(new Button()));
What happens is I end up with a vector of unique_ptr
s in mButtons and a vector of raw pointers in mListenerList pointing to the same dynamically allocated Button objects. I do not want smart and raw pointers pointing to the same object.
Ideally, I would like a vector of shared_ptr
s in mButtons and a vector of weak_ptr
s in mListenerList pointing to the dynamically allocated Button objects while allowing EventHandler to register every object on creation. Is this possible?