I have one QNetworkAccessManager to handle all my requests. The manager can receive an action to send a post request at anytime the application is running. I noticed there is almost a 70s timeout time before a QNetworkReply finishes when there is no internet.
In the constructor of the class I create the manager with:
mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(requestFinished(QNetworkReply*)));
connect(mgr,SIGNAL(sslErrors(QNetworkReply *, const QList<QSslError> &)),this,SLOT(handleSSLErrors(QNetworkReply *, const QList<QSslError> &)));
The request are created with:
QNetworkReply * reply = mgr->post(request, payload);
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this,
SLOT(slotError(QNetworkReply::NetworkError)));
For the networkreplies I have a signal slot:
connect(mgr,SIGNAL(finished(QNetworkReply*)),this,SLOT(requestFinished(QNetworkReply*)));
I delete the QNetworkReply rep in the requestFinished method with rep->deleteLater();
.
With this I expect all QNetworkReply to be deleted automatically.
In the desctructor of the class I run
delete mngr
my thoughts: 0:00 I send a request. 0:01 I delete the mngr (which automatically deletes the onfinished slot) 1:10 the request finishes, there is no longer a slot so deleteLater() is not called.
What is the proper way to delete the 'QNetworkAccessManager', It is possible my appliation send a request every 60 seconds that timeouts for 70 seconds (meaning there is always an ongoing request). How can I delete the qnetworkmanager without creating memory leaks?
connect(mgr, &QNetworkAccessManager::destroyed, reply, &QNetworkReply::deleteLater);
QObjects offer the destroyed()
signal. So you can connect your managers destroyed()
with the open replys deleteLater()
. When your manager is destroyed all open replies will be deleted. In case the reply finishes with the manager still alive, you explicitly call the deleteLater()
as you already do, which will prevent the reply from lingering until you destroy the manager.