How to fix memory leak while inheriting from QObject?

半城伤御伤魂 提交于 2020-01-03 04:58:28

问题


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.


回答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?




回答2:


I guess you are failing to call:

 delete manager?


来源:https://stackoverflow.com/questions/18443808/how-to-fix-memory-leak-while-inheriting-from-qobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!