简体   繁体   English

如何安全删除QT :: QTcpSocket?

[英]How to safely delete a QT::QTcpSocket?

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

The socket is created as a child of the server, which means that it is automatically deleted when the QTcpServer object is destroyed . 套接字是作为服务器的子级创建的,这意味着销毁QTcpServer对象时会自动删除该套接字。 It is still a good idea to delete the object explicitly when you are done with it , to avoid wasting memory. 在完成处理后 ,还是要明确删除该对象,以避免浪费内存,这仍然是一个好主意。

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. 在我的应用程序中, QTcpServer生存很长时间(当连接关闭时它会与主机断开连接,但除非程序退出,否则它不会被破坏),并且它接受大量QTcpServer::nextPendingConnection并占用大量内存。

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? 我应该如何删除旧的QTcpSocket对象,然后再切换到下一个未决的对象以节省内存,同时又要避免重复删除?

Is delete ok in this case? 在这种情况下可以delete吗?

Is delete ok in this case? 在这种情况下可以删除吗?

Yes, thanks to the cleverness of Qt's object design. 是的,感谢Qt的对象设计的巧妙之处。

In particular, QTcpSocket derives (eventually) from Object, and the QObject destructor method contains this code at the end: 特别是,QTcpSocket(最终)从Object派生,并且QObject析构函数方法在末尾包含以下代码:

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

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. 因此,删除QTcpSocket对象将自动从其父对象(在本例中为QTcpServer)的子代列表中删除QTcpSocket,因此在销毁QTcpServer对象时不会进行重复删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM