2013-02-06 352 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後面的對象。