[Interest] Who disconnects lambda expression slots?
Nikos Chantziaras
realnc at gmail.com
Sat Dec 15 02:45:56 CET 2012
On 15/12/12 03:12, Thiago Macieira wrote:
> On sábado, 15 de dezembro de 2012 02.53.58, Nikos Chantziaras wrote:
>> Since it's now possible to use lambdas as slots:
>>
>> connect(sender, &SenderClass::connected, [this] () {
>> this->doSomething();
>> };
>>
>> I have to wonder what is supposed to happen when the object where the
>> lambda appears gets destroyed. In this particular example, if the
>> lambda executes, dereferencing 'this' is no longer valid.
>>
>> The documentation:
>>
>> http://qt-project.org/doc/qt-5.0/qtcore/qobject.html#connect-5
>
> Note that connect() returns a QMetaObject::Connection object now and there's a
> disconnect() overload that takes such an object.
>
> Also note how connecting to a lambda changes the delivery behaviour during
> destruction. That is:
>
> connect(sender, SIGNAL(connected()), SLOT(doSomething));
> versus your example. During the destruction of this class, delivery to
> doSomething will be stopped due to the virtual table being destroyed, but the
> lambdas won't. You may end up calling this->doSomething() when the class is no
> longer valid.
So I take it that means we should always manually disconnect in such
cases. Thinking about it, it seems possible to have done this
automatically, but only for QObjects and through a connect() function
that would accept:
connect(const QObject* sender, PointerToMemberFunction signal,
const QObject* receiver, Functor functor);
In that case, connect() would be able to know when 'receiver' gets
destroyed and automatically do a disconnect.
Was something like this actually considered when designing the new
connection mechanism? Is it in any TODO list? :-)
More information about the Interest
mailing list