[Interest] Signal/Slot connection fails, even though QMetaObject::activate is called

Matthew Woehlke mwoehlke.floss at gmail.com
Fri Feb 14 21:01:34 CET 2020


On 07/02/2020 19.10, Tony Rietwyk wrote:
> Does it work if you don't pass 'this' as the third argument to connect? 
> I never use that particular overload of connect. I usually pass the
> lambda as the third argument.

That scares me. The third argument is the context in which the slot
runs, i.e. the "receiver". If your lambda contains any state, not
passing a context risks the slot being called after whatever owns that
state has ceased to exist, which will likely lead to UB. (It also risks
the lambda running in the wrong thread.)

Basically, if your lambda has *any state at all*, you should *always*
pass a context. The context should be a QObject which owns that state
and whose thread can safely use the state.

The context should only be omitted if your lambda is stateless, and even
then I'd avoid doing so unless you really need to, or are making a
deliberate choice that no one should "own" the connection.

-- 
Matthew


More information about the Interest mailing list