I was thinking about writing method like this:
QString getData() {
QNetworkReply *reply = getReply();
reply->deleteLater();
return QString::fromUtf8(reply->readAll()).trimmed();
}
Is it safe?
If I’m forced to write this like this:
QString getData() {
QNetworkReply *reply = getReply();
QString result = QString::fromUtf8(reply->readAll()).trimmed();
reply->deleteLater();
return result;
}
I’m copping QString twice (am I?, once it’s put into result and second when returning it by value), which I wanted to avoid.
From the deleteLater docs:
So what you are doing there is safe. Obviously handing out references or pointers to that object (or its members) that might be persisted is wrong. But if you’re returning copies, you’re fine.
But what you’re doing might or might not do what you want to do.
readAlldoesn’t block, it returns the data currently available. Meaning that a single call toreadAllmight only read a partial response – unless you’ve ensured that all data has arrived through other means.Other things to note, from the docs:
So the only thing to worry about when doing this type of thing would be calling functions that somehow re-enters the "current" event loop. But that won’t happen if that is done via
QCoreApplication::processEvents:So that’s covered too. The deferred deletion logic is pretty complex, but safe under normal circumstances. If you’re digging very deep into the Qt internals (or calling code that might do something fishy there), be defensive. But for normal code flow,
deleteLateris safe as long as you don’t have dangling references (or pointers) that might persist.