本文介绍了如何安全地删除 QT::QTcpSocket?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

QTcpSocket * QTcpServer::nextPendingConnection() [虚拟]

socket 是作为服务器的子节点创建的,这意味着它是当 QTcpServer 对象被销毁时自动删除.这是完成后显式删除对象仍然是一个好主意,避免浪费内存.

在我的应用程序中,一个 QTcpServer 存在很长时间(当连接关闭时它与主机断开连接,但除非程序退出,否则它永远不会被破坏),并且它接受了很多 QTcpServer::nextPendingConnection 并占用大量内存.

In my application, a QTcpServer lives for a long time (it disconnects from host when connection is closed but is never destroyed unless the program exits), and it accepts a lot of QTcpServer::nextPendingConnection and takes a lot of memory.

如何在切换到下一个挂起的对象之前删除旧的QTcpSocket对象以节省内存,同时避免双重删除?

How should I delete the old QTcpSocket object before switching to the next pending one to save memory, while at the same time avoid double-delete?

在这种情况下delete可以吗?

推荐答案

是的,感谢 Qt 对象设计的巧妙.

Yes, thanks to the cleverness of Qt's object design.

特别是,QTcpSocket 派生(最终)自 Object,而 QObject 析构函数方法最后包含此代码:

In particular, QTcpSocket derives (eventually) from Object, and the QObject destructor method contains this code at the end:

if (d->parent)        // remove it from parent object
    d->setParent_helper(0);

因此删除 QTcpSocket 对象将自动从其父对象(在本例中为 QTcpServer)的 children-list 中删除 QTcpSocket,因此在销毁 QTcpServer 对象时不会出现双重删除.

So deleting the QTcpSocket object will automagically remove the QTcpSocket from the children-list of its parent object (in this case, the QTcpServer), so there will be no double-delete when the QTcpServer object is destroyed.

这篇关于如何安全地删除 QT::QTcpSocket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!