【问题标题】:How to use QDBusPendingCallWatcher properly?如何正确使用 QDBusPendingCallWatcher?
【发布时间】:2013-01-21 11:56:40
【问题描述】:

我正在尝试使用QDBusPendingCallWatcher 来观看异步调用。一些示例代码如下:

{
    // interface = new QDBusInterface(...);
    QDBusPendingCall pcall = interface->asyncCall("query");
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, this);
    QObject::connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(handler(QDBusPendingCallWatcher*)));
}

和处理函数:

void Client::handler(QDBusPendingCallWatcher* call)
{       
    QDBusPendingReply<QString> reply = *call; 
    // do something
}

我的问题是:

  1. 看起来QDBusPendingCallWatcher 使用shared data pointer inside,不手动删除watcher 指针是否安全?只是离开范围而忘记它?

  2. 如果我可以让pendingcall 的智能指针完成所有操作,我可以在我的班级中只使用一个QDBusPendingCallWatcher 指针来监视所有异步调用吗?像这样:

    {
        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*)));
    }
    

    这会造成灾难吗?还是应该为每个调用使用多个指针?

谢谢!

【问题讨论】:

    标签: qt qtdbus


    【解决方案1】:

    仔细看看QDBusPendingCallWatcher documentation

    上述代码连接的槽可能类似于以下内容:

    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();
    }
    

    QObject::deleteLater 的调用是关键:这意味着 Qt 将在执行返回事件循环后立即删除该对象。

    只要你在Client::handler(...) 中调用deleteLater,你就不需要——更准确地说你不应该——在任何地方调用delete watcher;。唯一需要确保的是在槽返回后没有人使用call 后面的对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-04
      • 2012-07-12
      • 2021-10-24
      • 2011-12-22
      • 2020-10-14
      • 2015-12-10
      • 2021-01-15
      • 2018-01-31
      相关资源
      最近更新 更多