0

我有一个简单的课程:

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 开始,我不明白为什么我在这里泄漏内存。

4

2 回答 2

1

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

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

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

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

另外,看看

Qt中的内存管理?

于 2013-08-26T12:22:18.833 回答
0

我猜你没有打电话:

 delete manager?
于 2013-08-26T12:18:09.277 回答