boost signals connection management

会有一股神秘感。 提交于 2019-12-05 03:31:23

问题


I've been bashing my head for the last two nights trying to figure this out with no positive results. There is the thing, in boost signals, every time I want to connect, say, a member function of one class to another's class signal, I have to save the resulting connection in a variable if I want to disconnect later. If later on, I want to connect the same member function to some other class signal (the member function is still connected with the previous class signal) I have to save this new connection in order to manage it too. My question is, is there any way to avoid this?


回答1:


You shouldn't need to keep connection instances around, you should be able to disconnect from a signal by passing the original callable to signal::disconnect, as described in the Boost.Signals tutorial. With member functions the problem is rather the fact that you cannot pass them directly to signal, you either wrap them in custom function objects, which would then be available as arguments to signal::disconnect or you use Boost.Bind, which by itself wouldn't be very useful as you cannot conveniently declare its return type. However that problem can be solved using Boost.Bind together with Boost.Function.

I hope I answered your question.




回答2:


Scoped Connections

Alternatively you could assign the returned connection to a variable of type signal::scoped_connection. It's a type of connection which automatically disconnects on destruction or reassignment. This effectively limits a signal-slot connection lifetime to a particular scope.

For example when you reassign myConnection, the previous connection is automatically disconnected:

scoped_connection myConnection = someObject.Signal.connect(MyHandler);
myConnection = totallyDifferentObject.Signal.connect(MyHandler);


Automatic Connection Management

In our project, we usually declare member variables as scoped connections. So their scope matches the live time of the particular object instance the belong to. This is a convenient way to automatically disconnect any signals an object instance is connected to when it is being destructed. Without scoped connections you have to manually disconnect yourself in the destructor. If you neglect to disconnect instances when they're destroyed, you'll end up invoking invalid signal handlers which will crash your programs.



来源:https://stackoverflow.com/questions/7496225/boost-signals-connection-management

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!