如何在继承QObject时修复内存泄漏?

时间:2013-08-26 12:13:57

标签: c++ qt memory-leaks visual-leak-detector

我有一个简单的课程:

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此时指向内存泄漏:

manager = new QNetworkAccessManager(this);

我该如何解决?我并不坚持认为这是最好的解决方案,但我只是从QT开始,我不明白为什么我在这里泄漏内存。

2 个答案:

答案 0 :(得分:1)

这是因为您通过“this”将父对象指针传递给

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

和所有权,因此Qt内存模型将负责删除对象,请参阅

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

另外,请查看

Memory management in Qt?

答案 1 :(得分:0)

我猜你没打电话:

 delete manager?