问题
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