On the client side, when a new connection arises, I try to create a smart socket pointer to add it to QMap and continue working with them.

QSslSocket *client = dynamic_cast<QSslSocket*>(nextPendingConnection()); Q_ASSERT(client); client->setProperty("type", QString("CLIENT")); std::shared_ptr<QSslSocket> sock = std::make_shared<QSslSocket>(client); ... 

But now sock-> property ("type"). ToString () returns an empty string, and also we cannot write anything to the socket, since it is closed.

If you work with the client, then everything is fine, including in the context of other slots.

Tried with QSharedPointer, the same picture

 QSharedPointer<QSslSocket> sck = QSharedPointer<QSslSocket>::create(client); 

Explain this behavior. Debian, gcc 4.7.2

UPD Hmm, and if you transfer to QMap just SharedPointer (client), it works ...

    1 answer 1

    Try not to use smart shared-use pointers ( shared_ptr / QSharedPointer ) with QObject , since the latter do not provide copying, and the duration of the "life" is usually controlled by passing a pointer to the parent to its child objects (do not confuse with inheritance). For the same reason, it is not recommended to use single-own pointers ( unique_ptr / QScopedPointer ), since It is required to declare to the child QObject without fail that he does not have a parent .

    In your situation with QSslSocket , this is the case. The object has already been assigned a parent (most likely QTcpServer ), and as soon as it goes to the liquidation process, it will automatically destroy the QSslSocket instance that you are trying to pack into the smart pointer. What happens next, I think, is quite obvious. Therefore, if there is still a reason to "hide" the QObject heir in a smart pointer, do not forget to do the following beforehand:

     QSslSocket *client = qobject_cast<QSslSocket*>(nextPendingConnection()); client->setParent(nullptr); 

    Despite some inconsistency with STL on the designated topic, Qt still has smart pointers designed to work with QObject heirs. This is a QPointer . Something similar to him is std::weak_ptr and of course QWeakPointer . This type of pointers does not fully own objects, but makes it possible to determine the fact of their "life" or "death." And unlike similar pointers, you can insert an object (a QObject heir) into QPointer at any time, and not just at the time of creation.

    • Thanks for the answer. Explain the example of working with sockets in Qt: I am in the override method incomingConnection (qintptr handle), create a new socket new QSslSocket, assign it a handle and throw it further into addPendingConnection (sock). How, in this case, to organize a safe cleaning of memory when, say, a connection is broken? If you pass the parent QTcpServer, then cleaning will be only at the completion of the server, as I understood. Is it possible without new / delete? - magrif