On en.so came across the ability to turn off the signal from the lambda in this way:

QMetaObject::Connection *conn = new QMetaObject::Connection(); QSharedPointer<QMetaObject::Connection> pconn(conn); (*pconn) = QObject::connect(my_obj, &MyClass::mySignal, [this,pconn]() { QObject::disconnect(*pconn); }); 

Is there a memory leak and how else is it possible to perform the indicated operation?

    1 answer 1

    No, there is no memory leak. In the form that you want to make, I'm afraid the choice is small. One way or another, you'll have to use a pointer. The alternative is to pass the connection as a signal argument, or to save it in the class field and refer to this in the lambda.

    • Thank you for the answer. See, I’m confused that QObject::connect() returns a QMetaObject::Connection object created on the stack, whereas QSharedPointer stores an object created on the heap. As a result, the pointer is substituted for the connection object. Then, in theory, the object in the heap should get lost ... Or am I missing something? .. - alexis031182
    • @ alexis031182, miss the fact that the pointer does not change. There is a replacement of what the pointer points to. The pointer itself remains the same, it’s just that what it’s pointing to now has other data — the data that it received after executing operator=(Connection && other) of the Connection - ixSci class
    • Right, you are right. And I was looking at the overridden operators of QSharedPointer itself, overlooking QMetaObject::Connection . Thank. - alexis031182