-
Notifications
You must be signed in to change notification settings - Fork 65
Open
Labels
Description
I use qtpromise a lot in my project and I am constantly running into next situation
static QtPromise::QPromise<void> DoSomething()
{
return QtPromise::resolve().delay(5000);
}
////
struct Foo : public QObject {
void doSomethingAndDoSomethingElse()
{
QPointer<Foo> self(this);
DoSomething().then([self] {
if(self) {
// do something with self.
qDebug() << "Self is ok";
}
else {
qDebug() << "Foo already deleted";
}
});
}
};
Foo *foo = new Foo;
foo->doSomethingAndDoSomethingElse();
// here foo gets deleted(by deleteLater for instance)
So it can happen that Foo gets deleted before promise is resolved, and since function is called as callback I need to check if this is still valid in some way otherwise I get segfault.
I was thinking a lot about it and it seems like a pretty common thing.
I see 3 ways how to resolve this situation.
- Check
thisas I am doing it right now. - Store started promises and wait for them in destructor.
- Try to support same behavior as Qt signal & slots system in terms of executing slot in receivers context.
I like 3rd case the most but it requires changes to the library(which I can do). I want to discuss here if it makes sense at all and if you see any problems with it.
So the idea is to provide executing context to continuations, introduce new call like,thenVia(QObject *, callback)or something likethen(callback).via(QObject*)which will be used as context for delivering callback. If such functionality exists then my use case will be resolved just by using context for continuations since if context is already deleted, callback won't be executed(same behavior with slots). Implementation wise it shouldn't be that hard to do it, since it requires just some modifications toqtpromise_defer.
Looking forward to discussing it