2

Suppose, there is a lambda connected to a signal as below:

connect(pObject, &Object::mySignal, [] () { lambda; });

Will below statement disconnect the lambda automatically?

disconnect(pObject, &Object::mySignal, nullptr, nullptr);

I am asking this, because in the QObject::disconnect's documents there are 2 contradicting statements:

2 Disconnect everything connected to a specific signal:
disconnect(myObject, SIGNAL(mySignal()), nullptr, nullptr);

and

Note: It is not possible to use this overload to disconnect signals connected to functors or lambda expressions. That is because it is not possible to compare them. Instead, use the overload that takes a QMetaObject::Connection`

Related: Disconnecting lambda functions in Qt5

iammilind
  • 68,093
  • 33
  • 169
  • 336
  • This seems fairly easy to test. Have you tried it? – JarMan Aug 03 '22 at 13:09
  • @JarMan, not really. We are facing some undefined behaviour related to `QSslSocket` in our code on random basis. So now we are investigating all the signal/slots one by one. We are not sure, why the crash happens, but this is one of the topmost suspicions. – iammilind Aug 03 '22 at 13:47

1 Answers1

3

Just to clarify, the two quotes you gave are in fact from different QObject::disconnect overloads.

In summary, the call...

disconnect(myObject, &MyObject::mySignal, nullptr, nullptr);

should disconnect everything connected to the MyObject::mySignal signal of the MyObject instance pointed to by myObject -- including lambdas/functors.

I think the perceived contradiction comes from the fact that the second statement (the "Note") is rather badly worded. What it should state is...

Note: It is not possible to use this overload to disconnect signals connected to specific functors or lambda expressions. ...

Hence, given the 'mocked up' code...

QPushButton *pb = ...
auto slot = [](bool checked) { /* Some useful stuff. */ };
connect(pb, &QPushButton::clicked, this, slot);

it is not then possible to do...

disconnect(pb, &QPushButton::clicked, this, slot);

If, however, you do as the quote says and...

...use the [disconnect] overload that takes a QMetaObject::Connection

then the following should work...

auto connection = connect(pb, &QPushButton::clicked, this, slot);
disconnect(connection);

[Note: I don't have Qt installed on the box, so the above is untested.]

iammilind
  • 68,093
  • 33
  • 169
  • 336
G.M.
  • 12,232
  • 2
  • 15
  • 18