std::function as callback, is unregistration possible?

前端 未结 1 1811
离开以前
离开以前 2021-02-05 14:26

The question is strictly about std::function and not boost::function. See the Update section at the bottom of this question for more details,

1条回答
  •  别那么骄傲
    2021-02-05 14:52

    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.

    0 讨论(0)
提交回复
热议问题