0

I'm currently trying to implement an event manager in C++. In principle it keeps a map of event types (uint64_t) to a list of boost::function<void(const IEventDataPtr&)>s.

User can register new listeners by calling EventManager::add(boost::function<void(const IEventDataPtr&)> delegate, EventType event). However, a user might want to deregister their listener later. This would involve finding this particular function object and removing it from the respective list.

I know that boost::function is generally not comparable. When playing around in the debugger I found that by comparing functor.members.func_ptr I could actually do what I was trying to do. It works as expected for lambdas, boost::bind, static member functions and regular functions. Is this safe to do? Are there any gotchas?

My expectation would be for the same object (i.e. the same lambda, function, etc. pp.) to have the same address, that is not shared with others.

  • 2
    use an atomic counter to generate a unique ID for each callback and store it along side the callback in your map, return the ID from `add` and the caller can then pass the ID to `remove` – Alan Birtles Jun 14 '21 at 20:15
  • @AlanBirtles Using your suggestion, if one were to register one listener for multiple events (i.e. multiple `add` calls), there would be no way to implement something like `removeForAllEventTypes()`. Or checking if a user already registered a particular callback. – Frederic Schönberger Jun 14 '21 at 20:57
  • By relying un undocumented implementation details, your code might be not portable or might not works as expected in some cases you haven't tried yet. You should really do as suggested by Alan... – Phil1970 Jun 14 '21 at 22:23

0 Answers0