Search code examples
c++boostlambdaboost-signals2

boost signals auto disconnect lambda slot


I'm trying to do this:

boost::signals::connection c = somesignal.connect(
[c]()->void{
    // Do something
    c.disconnect();
})

Will this cause problems?

The connection c is assigned only after connect.

lambda needs to be initialized before connect.

It seems capture by value would not work. However, I can not capture by reference, since c is only a local variable.

If it is not a lambda, I can capture the "somesignal", and call somesignal.disconnect(slot). But in the case of a lambda, the slot is itself.


Solution

  • Use extended slot, Signals2 passes the connection object to it. It's designed primarily for thread-safety, but you can utilize it for your purposes as well:

    somesignal.connect([](const connection &c)->void 
    {
      // Do something
      c.disconnect();
    });
    

    (By the way, as opposed to what the title implies, it's actually not an "auto-disconnection", but the manual one. To disconnect slots automatically, one could use the tracking mechanism.)