qt 的QNetworkAccessManager的使用和防止内存泄漏

今天项目中用到了http协议,大致看了一下QNetworkAccessManager这个类,发现通过这个类调用了get或者post请求后获取结果居然是通过信号和槽来实现的,结果返回是通过void finished(QNetworkReply * reply)这个信号传出来的,那么问题来了,由于不知道请求的结果什么时候下载完,既不知道这个finished信号什么时候抛出,那么也不知道这个QNetworkAccessManager对象该在什么时候delete。

这个可不好办呐,不delete的话就会内存泄漏,对于程序员来说这是很恐怖的事~

我觉得qt应该也不会让这种bug出现吧,果不其然,在文档对finished信号的描述中有这么一句话:

”Note: Do not delete the reply object in the slot connected to this signal. Use deleteLater().“

意思就是如果连接了该信号,就不要delete这个对象,用deleteLater()这个函数。

deleteLater(),顾名思义就是延迟delete的作用,我随后认真看了一下deleteLater的文档和上网搜寻了一下相关的资料,发现实际上deleteLater也不是想象中那么靠谱。。

void QObject::deleteLater()
Schedules this object for deletion.


The object will be deleted when control returns to the event loop. If the event loop is not running when this function is called (e.g. deleteLater() is called on an object before QCoreApplication::exec()), the object will be deleted once the event loop is started. If deleteLater() is called after the main event loop has stopped, the object will not be deleted. Since Qt 4.8, if deleteLater() is called on an object that lives in a thread with no running event loop, the object will be destroyed when the thread finishes.


Note that entering and leaving a new event loop (e.g., by opening a modal dialog) will not perform the deferred deletion; for the object to be deleted, the control must return to the event loop from which deleteLater() was called.


Note: It is safe to call this function more than once; when the first deferred deletion event is delivered, any pending events for the object are removed from the event queue.


从文档中可以看出,调用deleteLater的对象将在程序控制返回事件循环后被delete,也就是控制权回到QApplication时才删除

发布了4 篇原创文章 · 获赞 0 · 访问量 9475

猜你喜欢

转载自blog.csdn.net/yangkping123/article/details/46786147