Delete sender in a separate slot

I have an object that emits 3 different signals, and I would like to transmit these signals, as well as delete them. This object is located in another object that will act as the emitter of these signals.

I would usually like to do this as follows:

void SomeClass::someSideFunction() { Request* request = _StorageProvider.insert("somedata"); connect(request, SIGNAL(succeded()), this, SLOT(handleSucceded())); connect(request, SIGNAL(failed()), this, SLOT(handleFailed())); connect(request, SIGNAL(alreadyExists()), this, SLOT(handleAlreadyExists())); } void SomeClass::handleSucceded() { Request* request = qobject_cast<Request*>(sender()); if(request != NULL) request ->deleteLater(); emit succeded(); } void SomeClass::handleFailed() { Request* request = qobject_cast<Request*>(sender()); if(request != NULL) request ->deleteLater(); emit failed(); } void SomeClass::handleAlreadyExists() { Request* request = qobject_cast<Request*>(sender()); if(request != NULL) request ->deleteLater(); emit alreadyExists(); } 

Is there a better way to do this? Although the "request" is a child of storageProvider, there is a way for many requests that I wait to just wait to remove them until the parent dies.

I was thinking of some kind of solution like this:

 connect(request, SIGNAL(succeded()), this, SIGNAL(succeded())); connect(request, SIGNAL(failed()), this, SIGNAL(failed())); connect(request, SIGNAL(alreadyExists()), this, SIGNAL(alreadyExists())); connect(request, SIGNAL(succeded()), this, SLOT(memoryHnadler())); connect(request, SIGNAL(failed()), this, SLOT(memoryHnadler())); connect(request, SIGNAL(alreadyExists()), this, SLOT(memoryHnadler())); 

If the memory handler removes the sender, if it exists. What would be the disadvantage of this approach and what could be better?

Please note that the object will emit only one of these signals when it is done!

+4
source share
2 answers

I do not see a flaw in your second approach. Qt will send signals first, and then a memory handler, as it runs in the same order in which you declare the connections.

The memory handler must be the only one that removes the Request object.

Another approach is to emit signals with the Request object as an argument, and then rely on a user slot to remove them. But if the user slot is not declared, you will continue to grow memory ...

+2
source

The option is to have the query schedule do its own deletion using QObject :: deleteLater (). Like this:

 void Request::emitSucceeded() { emit succeeded(); deleteLater(); } void Request::emitFailed(int errorCode, const QString& errorString ) { m_errorCode = errorCode; m_errorString = errorString; emit failed(); deleteLater(); } 

For example, the KDELib base class for asynchronous KJob operations uses this template (unless explicitly disabled using setAutoDelete (false)),

+3
source

Source: https://habr.com/ru/post/1412305/


All Articles