When to delete QNetworkReply?

The usual way to use QNetworkAccessManager and QNetworkReply is:

QNetworkAccessManager nam;
voif fun()
{
    QNetworkRequest request;
    request.setUrl(QUrl("https://myprogrammingnotes.com"));
    connect(&nam,SIGNAL(finished(QNetworkReply*)),this,SLOT(replyFinished(QNetworkReply*)));
    QNetworkReply *reply=nam.get(request);
}

void replyFinished(QNetworkReply* reply)
{
    reply->readAll();
}

According to https://doc.qt.io/qt-5/qnetworkaccessmanager.html, you need to delete the QNetworkReply object yourself:

Note: After the request has finished, it is the responsibility of the user to delete the QNetworkReply object at an appropriate time. Do not directly delete it inside the slot connected to finished(). You can use the deleteLater() function.

There are two occurrences of the QNetworkReply object, one is the return value of QNetworkAccessManager::get, the other is in the slot as the parameter of the slot. The two pointers point to the same object. The question is which one to delete?

If you delete the QNetworkReply object in fun(), you’ll find the slot will never be called. So the right place to delete the QNetworkReply object is in the slot, after you use it(like read data form it). Of course, you need to use deleteLater rather than delete as told by https://doc.qt.io/qt-5/qnetworkreply.html:

Note: Do not delete the object in the slot connected to the errorOccurred() or finished() signal. Use deleteLater().

So the slot function should be modified as:

void replyFinished(QNetworkReply* reply)
{
    reply->readAll();
    reply->deleteLater();
}

What if you do not delete the QNetworkReply object? Well, you will expect a memory leak. After calling deleteLater on the QNetworkReply object, it will be deleted when entering the main event loop. Note that the QNetworkReply object is only deleted in the main event loop, not in the event loop created by yourself, nor the event loop for a modal dialog.

Whenever you call get, post, etc. on a QNetworkAccessManager object, a new QNetworkReply object will be created. The old ones will be lost if not saved. So, if you forget to delete the old QNetworkReply objects, they will eat up memory gradually.

 

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!
Posted in

Leave a Reply