The question is strictly about std::function
and not boost::function
. See the Update section at the bottom of this question for more details,
Since you can't test for element identity in the container, it's probably best to use a container (such as std::list
) whose iterators do not invalidate when the container is modified, and return iterators back to registering callers that can be used to unregister.
If you really want to use vector
(or deque
), you could return the integral index into the vector/deque when the callback is added. This strategy would naturally require you to make sure indexes are usable in this fashion to identify the function's position in the sequence. If callbacks and/or unregistration is rare, this could simply mean not reusing spots. Or, you could implement a free list to reuse empty slots. Or, only reclaim empty slots from the ends of the sequence and maintain a base index offset that is increased when slots are reclaimed off the beginning.
If your callback access pattern doesn't require random access traversal, storing the callbacks in a std::list
and using raw iterators to unregister seems simplest to me.