C++:析构函数级联期间的回调和系统计时器事件
假设在 OO 设计中,对象相互调用,一段时间后,被调用的对象回调发起对象(调用和回调)。在正常程序终止期间,当调用析构函数时,是否有某种承诺不会调用系统计时器,并且不会有对象启动回调?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有一个非常棒的库可以处理此类调用,当然它是 Boost 库。
看Boost.Signals2,即使在多线程应用程序 :)
特别注意使用
boost::trackable
类,以便对象销毁在发生之前自动使调用无效。注意:Boost.Signals(其祖先)具有几乎相同的功能,但不是线程安全的
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.
不,没有承诺。
有两种方法可以处理此问题:
拥有一个对象可以在销毁时调用的取消注册函数,这保证在终止后不会调用任何回调 -
CancelAllCallbacks()
或类似的。有一个弱引用机制,如前面提到的weak_ptr,只有在成功获取强引用时才调用回调。
通常,第一个选项就足够了,除非可以异步调度或调用回调 - 那么您就没有同步方法来阻止已计划调用的回调,或者实际上正在调用的回调(或来自现在)在不同的线程中。
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.