Slots aren't expected to exist indefinately after they are connected. Often slots are only used to receive a few events and are then disconnected, and the programmer needs control to decide when a slot should no longer be connected.
Signal/slot disconnections occur when any of these conditions occur:
-The connection is explicitly disconnected via the connection's disconnect method directly, or indirectly via the signal's disconnect method or scoped_connection's destructor.
-A trackable object bound to the slot is destroyed.
-The signal is destroyed.
Seg 1: Disconnecting slots.
boost::signals::connection c = sig.connect(HelloWorld());
if (c.connected()) {
// c is still connected to the signal
sig(); // Prints "Hello, World!"
}
c.disconnect(); // Disconnect the HelloWorld object
assert(!c.connected()); //c isn't connected any more
sig(); // Does nothing: there are no connected slots
Seg 2:
boost::signals::connection c = sig.connect(HelloWorld());
sig(); // Prints "Hello, World!"
c.block(); // block the slot
assert(c.blocked());
sig(); // No output: the slot is blocked
c.unblock(); // unblock the slot
sig(); // Prints "Hello, World!"
Slots in the Boost.Signals library are created from arbitrary function objects, and therefore have no fixed type. However, it is commonplace to require that slots be passed through interfaces that cannot be templates. Slots can be passed via the slot_type
for each particular signal type and any function object compatible with the signature of the signal can be passed to a slot_type
parameter.
Seg 3:
class Button
{
typedef boost::signal<void (int x, int y)> OnClick;
public:
void doOnClick(const OnClick::slot_type& slot);
private:
OnClick onClick;
};
void Button::doOnClick(
const OnClick::slot_type& slot
)
{
onClick.connect
(slot);
}
void printCoordinates(long x, long y)
{
std::cout << "(" << x << ", " << y << ")/n";
}
void f(Button& button)
{
button.doOnClick(&printCoordinates);
}
The doOnClick
method is now functionally equivalent to the connect
method of the onClick
signal, but the details of the doOnClick
method
can be hidden in an implementation detail file.