有一个纠结的问题,现做一个HTTP客户端,使用QNetworkAccessManager发现有内存泄漏现象,特意写了一个测试代码,如下:
nettest.h
- C/C++ code
#ifndef NETTEST_H#define NETTEST_H#include <QtGui/QWidget>#include "ui_nettest.h"#include <QNetworkAccessManager>#include <QNetworkRequest>#include <QNetworkReply>class NetTest : public QWidget{ Q_OBJECTpublic: NetTest(QWidget *parent = 0); ~NetTest();private: Ui::NetTestClass ui; QNetworkAccessManager *qnam; QNetworkRequest qnr;public slots: void onSend(); void accept(QNetworkReply *r);};#endif // NETTEST_H
nettest.cpp
- C/C++ code
#include "nettest.h"#include <QDebug>NetTest::NetTest(QWidget *parent) : QWidget(parent){ ui.setupUi(this); connect(ui.pushButton,SIGNAL(clicked()),this,SLOT(onSend())); qnr.setUrl(QUrl("http://www.baidu.com/")); qnam=new QNetworkAccessManager(); connect(qnam, SIGNAL(finished(QNetworkReply *)), this,SLOT(accept(QNetworkReply *)));}void NetTest::onSend(){ qDebug()<<"发送数据!"; qnam->get(qnr);}void NetTest::accept(QNetworkReply *r){ qDebug()<<"接收数据!"; qDebug()<<r->readAll();}
界面就是一个按钮,点击按钮触发onSend();数据接受完成后触发accept(QNetworkReply *r)输出数据。
在实际运行中,不断点击发送按钮,程序所使用的内存不断增长,在accept()中delete r;也没用。
本人平台Ubuntu11.04 Qt4.7
求高手指教,怎样释放每一次网络请求后占用的内存。
------解决方案--------------------
qnam=new QNetworkAccessManager(this);
&
void QNetworkAccessManager::finished ( QNetworkReply * reply ) [signal]
This signal is emitted whenever a pending network reply is finished. The reply parameter will contain a pointer to the reply that has just finished. This signal is emitted in tandem with the QNetworkReply::finished() signal.
See QNetworkReply::finished() for information on the status that the object will be in.
Note: Do not delete the reply object in the slot connected to this signal. Use deleteLater().
See also QNetworkReply::finished() and QNetworkReply::error().