这是我的代码。但我很困惑,我应该删除m_networkManager
。我能做到这一点
onRequestCompleted()
插槽,但问题是我的程序经常调用getData函数。
我担心的是这种情况:
getData()
被召唤。onRequestCompleted()
广告位被解雇之前,我的
程序再次调用getData()
。onRequestCompleted()
调用的getData()
被触发。 getData()
时实际分配了其他内存的m_networkManager。我认为这种情况会导致崩溃。
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();
}
答案 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();
}