c++ - How to fix memory leak while inheriting from QObject? -
i have 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 memory leak @ point:
manager = new qnetworkaccessmanager(this);
how fix it? don't insist best solution, starting qt , don't understand why leaking memory here.
this because pass parent object pointer via "this" to
http://qt-project.org/doc/qt-4.8/qnetworkaccessmanager.html#qnetworkaccessmanager
and ownership, therefor qt memory model take care of deleting object, see
http://qt-project.org/doc/qt-4.8/objecttrees.html
also, check out
Comments
Post a Comment