何时删除QNetworkAccessManager指针?

时间:2014-04-24 11:43:05

标签: c++ qt qt4

这是我的代码。但我很困惑,我应该删除m_networkManager。我能做到这一点 onRequestCompleted()插槽,但问题是我的程序经常调用getData函数。

我担心的是这种情况:

  1. getData()被召唤。
  2. onRequestCompleted()广告位被解雇之前,我的 程序再次调用getData()
  3. 第一个onRequestCompleted()调用的
  4. getData()被触发。
  5. 我的程序删除了第二次调用getData()时实际分配了其他内存的m_networkManager。
  6. 我认为这种情况会导致崩溃。

    void MyApp::getData() {
       QNetworkRequest request;
       request.setUrl(QUrl("http://www.domain.foo"));
    
       m_networkManager = new QNetworkAccessManager(this);   // Instance variable
       connect(m_networkManager, SIGNAL(finished(QNetworkReply*)),
               this, SLOT(onRequestCompleted(QNetworkReply *)));
    
       m_networkManager->get(request);
    
    }
    
    void MyApp::onRequestCompleted(QNetworkReply *reply) {
       QByteArray data = reply->readAll();
       reply->deleteLater();
       //m_networkManager->deleteLater();
    }
    

1 个答案:

答案 0 :(得分:4)

由于您每次调用QNetworkAccessManager时都会创建新的MyApp::getData()实例,因此您需要设法删除MyApp::onRequestCompleted()函数中的正确实例。您的代码中的问题是您始终删除最后创建的QNetworkAccessManager而不是导致插槽调用的那个。我的建议如下:

void MyApp::getData() {
   [..]
   // Not class member. Will be deleted in the slot.
   QNetworkAccessManager *networkManager = new QNetworkAccessManager(this);
   connect(m_networkManager, SIGNAL(finished(QNetworkReply*)),
           this, SLOT(onRequestCompleted(QNetworkReply *)));
   [..]
}

void MyApp::onRequestCompleted(QNetworkReply *reply) {
   QByteArray data = reply->readAll();
   reply->deleteLater();

   // Delete object whose signal triggered this slot.
   QObject *networkManager = sender();
   networkManager->deleteLater();
}