I have following code which works (but it should not work)
void myfunction(){
auto future = function_which_return_future();
auto *watcher = new QFutureWatcher<VariantTable>;
QObject::connect(watcher,&QFutureWatcher<VariantTable>::finished,this,[=](){
VariantTable table = future.result();
// do some stuff
delete watcher;
});
watcher->setFuture(future);
}
In this code, future goes out of scope but code inside watched's slot still get executed.
Is this because things are happening too fast and will my code may fail if things slowdown ? or its just that I don't need future after calling QFutureWatcher::setFuture ?
About the usage of the future in your slot:
Your lambda slot copies the future and the watcher pointer by values. Therefore when the slot is called, it does not care about the original future that went out of scope.
About the usage of the future inside the QFutureWatcher<VariantTable>
object:
If we take a look at the QFutureWatcher<T>::setFuture()
implementation in the source code of QFutureWatcher
, we can see:
template <typename T> Q_INLINE_TEMPLATE void QFutureWatcher<T>::setFuture(const QFuture<T> &_future) { if (_future == m_future) return; disconnectOutputInterface(true); m_future = _future; connectOutputInterface(); }
The private
member m_future
is defined as QFuture<T> m_future;
.
Apparently, the QFutureWatcher
owns its own copy of the given future.
Consequently, the original future is not used anymore after your instruction: watcher->setFuture(future);
To answer your question:
I have following code which works (but it should not work)
Actually, with what's previously mentioned, it should work :)
Note: It may not work as intended since the copied future in your slot and the copied future in your watcher object are two distinct instances.