How to fix memory leak while inheriting from QObject?

1.3k Views Asked by At

I have a simple class:

class HttpClient : public QObject
{

    Q_OBJECT
public:

    QNetworkAccessManager* manager;
    QNetworkReply* reply;

    HttpClient(){
        manager = new QNetworkAccessManager();
        reply = nullptr;
    }
    ~HttpClient(){
        delete reply;
    }

    public slots:
        void slotReadyRead(){
            cout << reply->readAll().data() << endl;
        }
        void slotNetworkError(QNetworkReply::NetworkError error){
            cout << reply->error() << endl;
        }
public:
    void Get(QUrl url){

        QNetworkRequest request;
        request.setUrl(url);

        reply = manager->get(request);
        connect(reply, SIGNAL(finished()), this, SLOT(slotReadyRead()));
        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(slotNetworkError(QNetworkReply::NetworkError)));
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    HttpClient client;
    client.Get(QUrl("http://localhost/SomeWebService.svc/GetData"));

    return a.exec();
}

Visual Leak Detector points to memory leak at this point:

manager = new QNetworkAccessManager(this);

How do I fix it? I don't insist that this is the best solution, but I am just starting with QT and I don't understand why I am leaking memory here.

2

There are 2 best solutions below

3
On

I guess you are failing to call:

 delete manager?
1
On

This is because you pass the parent object pointer via "this" to

http://qt-project.org/doc/qt-4.8/qnetworkaccessmanager.html#QNetworkAccessManager

and the ownership, therefor the Qt Memory Model will take care of deleting the object, see

http://qt-project.org/doc/qt-4.8/objecttrees.html

Also, check out

Memory management in Qt?