开发者

C++: Callbacks and system timer events during destructor cascade

Assume an OO design where objects call each other, and after a while the called upon objects callback the initiating objects (calls and callbacks). During normal program termination, while destructors are called, is there some kind of开发者_如何学编程 promise that no system timers will be called, and no object will initiate a callback?


There is a pretty awesome library to handle these kinds of calls, and of course it's a Boost one.

Behold Boost.Signals2, with guarantees of correctness even in multi-threaded application :)

Note in particular the use of boost::trackable class, so that objects destruction automatically invalidate the calls before they happen.

Note: Boost.Signals (its ancestor) has pretty much the same functionality, but isn't thread-safe


No, there is no such guarantee.

You need to write your code such that objects are not destroyed until you are finished using them.


  • boost's weak_ptr can help avoid accessing destroyed objects from callbacks in general, so probably also during termination. When using this, all objects that need to be called back, need a shared_ptr.
  • timers calling functions/callbacks are usually higher-end libraries, so it depend whether they support a stopAllTimers() functionality. If you have control over the library, it's probably not too difficult to implement, but you still need to know when to trigger it.


No, there is no promise.

There are two ways to handle this:

  • Have a deregistration function that an object can call on destruction, which guarantees no callbacks will be invoked after it terminates - CancelAllCallbacks() or similar.

  • Have a weak reference mechanism such as the weak_ptr that was already mentioned, to invoke the callback only if a strong reference has been successfully obtained.

Usually the first option is enough unless the callbacks can be scheduled or invoked asynchronously - then you don't have a synchronous way to prevent a callback that is already scheduled to be called, or is in fact being called now (or a few instructions from now) in a different thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜