0

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.

Qué Padre
  • 2,005
  • 3
  • 24
  • 39

2 Answers2

1

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?

Community
  • 1
  • 1
x29a
  • 1,761
  • 1
  • 24
  • 43
  • If I don't pass anything `manager = new QNetworkAccessManager();` , 'the same' thing occurs... So, I shouldn't worry about this leak? The whole thing is that Visual Leak Detector makes mistake or what? Sorry for my excessive stupidity. – Qué Padre Aug 26 '13 at 12:44
0

I guess you are failing to call:

 delete manager?
David Elliman
  • 1,379
  • 8
  • 15
  • @David Elliman, don't delete QObjects in a destructor, when you instantiated them with 'this'. – Greenflow Aug 26 '13 at 12:34
  • but the leak hasn't gone after I commented `//delete manager;` – Qué Padre Aug 26 '13 at 12:46
  • Your network manager certainly is no memory leak, but most likely your QNetworkReply. Without seeing more code it is hard to say, but your 'reply' in constructor and destructor does not make much sense. QNetworkAccessManager has a signal 'finished', which gives you a QNetworkReply object. **This** you have to delete. Same with other signals, which give you QNetworkReply objects. – Greenflow Aug 26 '13 at 14:44