I'm attempting to write a an observer pattern in c++
so I have a map that contains eventname -> vector of callback functions
The callback functions are stored in a vector as
std::unordered_map<std::string, std::vector<std::function<void(void *)>>>
std::function<void(void *)> fnCallback = std::bind(&wdog::onBark, this, std::placeholders::_1)
When I do this, I return a token to the listening code.
My usual pattern is to have a
weak_ptr<function<sig>> in the broadcaster, and the token is a
shared_ptr<void> (to the stored weak ptr).
When broadcasting, I filter out dead targets, then broadcast. Targets deregister by simply clearing, destroying or otherwise discarding their token. A vector of tokens in their instance is a reasonable way if they want to never deregister.
If you never broadcast this can lead to old dead resources hanging around needlessly, so in a public framework I might want something with bettter guarantees. But it is lightweight easy and fast otherwise.