QNetworkAccessManager uninstall error

I have a class 'Downloader' derived from a QObject that runs in a workflow. When the thread starts, the loader creates a QNetworkAccessManager object on the heap and starts requesting files. I keep track of how many files were requested and received. Once I got all the files, I delete the QNetworkAccessManager object and exit the stream. My problem is that deleting the manager object fails regardless of when and where I do it. I even tried manager-> deleteLater (). If I do not delete it, my code works fine, but I know there is a memory leak there. Here is a stripped down version of my code.

Creating a bootloader and a stream and setting up signals so that the start of the stream starts from the download, and when the download is completed, the stream stops:

QThread thread; Downloader downloader; downloader.setFiles(files); downloader.moveToThread(&thread); downloader.connect(&thread, SIGNAL(started()), SLOT(downloadFiles())); thread.connect(&downloader, SIGNAL(downloadsFinished()), SLOT(quit())); thread.start(); 

The implementation for the bootloader:

 void Downloader::downloadFiles() { QNetworkAccessManager *manager = new QNetworkAccessManager(); connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(finished(QNetworkReply*))); receivedCount = 0; requestCount = files.count(); for (QStringList::const_iterator pos = files.begin(); pos != files.end(); ++pos) { QUrl url(*pos); manager->get(QNetworkRequest(url)); } } void Downloader::finished(QNetworkReply *reply) { // *** Get the file data and process it *** // ++receivedCount; reply->deleteLater(); if (receivedCount == requestCount) { // manager->deleteLater(); emit downloadsFinished(); } } 

A recorded line will cause the application to crash. Even removing the manager in the Downloader destructor or installing the bootloader as the manager's parent will lead to the application crashing.

At first I tried to create the dispatcher as a regular member variable on the stack, but it causes errors because the manager will be created in the GUI thread, and then it will try to create children in another thread.

And before anyone says, “QNetworkAccessManager is asynchronous. Why use it in a workflow?” I have a reason. It should not be SUCH that one could do something like this.

+4
source share
1 answer

The only obvious problem is below, but I'm not sure if you posted all your code or not.

 void Downloader::downloadFiles() { QNetworkAccessManager *manager = new QNetworkAccessManager(); 

You create a local QNetworkAccessManager *manager in your method, but do not save a link to it, and then try to access it in the final () method.

You must assign new QNetworkAccessManager(); member variable!

+4
source

All Articles