Solved QtConcurrent::run with objects that are deleted
-
I have the following code:
auto future = QtConcurrent::run(this, &XMLexport::saveXml, fileName); auto watcher = new QFutureWatcher<bool>; QObject::connect(watcher, &QFutureWatcher<bool>::finished, [=]() { mpHost->xmlSaved(fileName); }); watcher->setFuture(future);
If my QFutureWatcher goes off when
mpHost
(aQPointer
) is already gone, bad things happen. What would be the best way of dealing with this? I don't care about callingxmlSaved()
if thempHost
is already gone. -
@Vadi2 said in QtConcurrent::run with objects that are deleted:
[=]() { if (mpHost) mpHost->xmlSaved(fileName); }
-
First thing I tried! It didn't work; I get a crash deep inside Qt then even though debugger says host is 0x0.
-
Yeah, thought that would be too easy... :/
-
Ah, try capturing by ref:
[&]() { if (mpHost) mpHost->xmlSaved(fileName); }
Since
=
captures by value, it may be that it copies the pointer value at the time you call connect() (so when object is still alive), which is no longer true later. Capturing by reference should work better. -
@Vadi2 said in QtConcurrent::run with objects that are deleted:
QObject::connect(watcher, &QFutureWatcher<bool>::finished, [=]() { mpHost->xmlSaved(fileName); });
That's the reason why you should avoid the connect() with three params...
QObject::connect(watcher, &QFutureWatcher<bool>::finished, mpHost, [=]() { mpHost->xmlSaved(fileName); });
-
That worked, but I'm not sure why and what does it mean for the
mphost
. Is there documentation I can read on this?I've already read https://github.com/KDE/clazy/blob/master/docs/checks/README-connect-3arg-lambda.md but it does not explain it well
-
Use the doc Luke ;-)
Short version: the
fourththird parameter is a "context" if the context gets delete, then then the disconnection follows and therefore in your case the lambda will not get executed.[Typo fixed ~kshegunov]