2

I'm writing a tcp based server using Qt.

I plan this server to be multithreaded, so my tcpserver class inherits from QTcpServer and overrides incomingConnection(). Everything is fine, except when it comes to deleting a user.

The TcpServer class manages a list of QSharedPointer<Client>. When I remove the said client from the list, it gets automatically deleted because of the smart pointer. My Client class owns a QSharedPointer<QTcpSocket> which means that the client's QTcpSocket gets deleted when the client is deleted.

Problem is, it seems that Qt tries to use this socket after its deletion, causing Segmentation Fault.

Should I manages a list for the sockets only, and call deleteLater() on them when I dont need them anymore? Or should I switch my socket's pointer in client class to a normal pointer?

void SlotSocketError(void)
{
  QTcpSocket sock = qobject_cast<QTcpSocket *>(QObject::sender());
  QSharedPointer<Client> client = GetClientFromSocket(sock);

  _clientList.removeAt(GetClientPositionInList(client));
}

 QList<QSharedPointer<Client> > _clientsList; // From TcpServer header.

 /* Client's class header */
 QSharedPointer<QTcpSocket> _socket;
4

2 回答 2

4

您需要在对象上使用 deleteLater。删除 QTCPSocket 后,可能会收到传入消息。它记录在助手中。你可以在这里找到一个例子:qthelp://com.trolltech.qt.472/qdoc/qt4-network.html

于 2011-09-20T14:52:37.830 回答
2

当您创建QSharedPointers 时,您可以将删除器传递给它们,以便它们将使用deleteLater而不是delete在您从列表中删除它们时使用。

在文档中也有一个例子可以做到这一点: http:
//doc.trolltech.com/latest/qsharedpointer.html#QSharedPointer-3

于 2011-09-25T14:08:45.980 回答