Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top