2013-02-06 269 views
2

我正在尝试使用QDBusPendingCallWatcher来观看异步呼叫。一些示例代码是这样的:如何正确使用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*))); 
    } 
    

    这会造成灾难吗?或者我应该为每个呼叫使用多个指针?

谢谢!

回答

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就会删除对象。

只要您拨打deleteLater里面Client::handler(...),你并不需要 - 更准确地说你不可以 - 呼叫delete watcher;任何地方。您必须确保的唯一一件事是在插槽返回后没有人使用call后面的对象。