I'm trying to use QDBusPendingCallWatcher
to watch an async call. Some sample code like this:
{
// interface = new QDBusInterface(...);
QDBusPendingCall pcall = interface->asyncCall("query");
QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, this);
QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(handler(QDBusPendingCallWatcher*)));
}
and handler function:
void Client::handler(QDBusPendingCallWatcher* call)
{
QDBusPendingReply<QString> reply = *call;
// do something
}
My questions are:
It looks like QDBusPendingCallWatcher
uses shared data pointer inside, is it safe to not manually delete the watcher
pointer? Just leave the scope and forget it?
If I can let the smart pointer of pendingcall to do all the tricks, can I use just one QDBusPendingCallWatcher
pointer in my class to watch all the async calls? Like this:
{
QDBusPendingCall pcall = interface->asyncCall("query");
watcher = new QDBusPendingCallWatcher(pcall, this);
QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(handleOne(QDBusPendingCallWatcher*)));
pcall = interface->asyncCall("anotherQuery");
watcher = new QDBusPendingCallWatcher(pcall, this);
QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(handleTwo(QDBusPendingCallWatcher*)));
}
Will this makes a disaster? Or should I use multiple pointers for each call?
Thanks!
Take a closer look at the QDBusPendingCallWatcher documentation:
The slot connected to by the above code could be something similar to the following:
void MyClass::callFinishedSlot(QDBusPendingCallWatcher *call)
{
QDBusPendingReply<QString, QByteArray> reply = *call;
if (reply.isError()) {
showError();
} else {
QString text = reply.argumentAt<0>();
QByteArray data = reply.argumentAt<1>();
showReply(text, data);
}
call->deleteLater();
}
The call of QObject::deleteLater is the key: This means Qt will delete the Object as soon as execution returns to the event loop.
As long as you call deleteLater
inside Client::handler(...)
, you don't need to - more precisely you musn't - call delete watcher;
anywhere. The only thing you have to ensure is that noone uses the object behind call
after the slot returns.