I was in #Qt irc channel, and I showed a small snippet of my code in a style that I heavily rely upon. It looks like this:
/* Get Reply from Server */
QPointer<QNetworkReply> reply;
{
QEventLoop waitForFile; // A QObject
connect(&m_NetworkAccessManager, &QNetworkAccessManager::finished, &waitForFile, &QEventLoop::quit);
reply = m_NetworkAccessManager.get(request);
waitForFile.exec();
disconnect(&m_NetworkAccessManager, &QNetworkAccessManager::finished, &waitForFile, &QEventLoop::quit);
}
I was told that the code was pretty strange, which does not surprise me. I tend to rely heavily on the stack, and am very keen to control lifecycle with {
and }
-- Basically my working principle has been
Delete all objects ASAP using scope.
In this case, the QEventLoop
does not need to exist beyond this scope, and its usefulness is only relative to QPointer<QNetworkReply> reply;
which is an added benefit for readability.
In any case, that code prompted the declaration:
You should always allocate qobjects on the heap
We had a bit of a discussion about this. Frankly I was shocked, as I operated under the idea that:
Fear QObject pointers, and only use them for very specific usecases such as:
- If a parameter is designed to be able to accept NULL values.
- If the object being passed to a function is large, and a reference can not be used.
- If the object will be added to a QList.
- If you are developing a GUI, where parent/child relationships are paramount
- If you are working with special types, like QFile or QThread, where copying instances of these objects is conceptually null. (You wouldnt want two QFile's of the same file.)
After giving my reasons, they stuck fairly hard to working under the principle of Always allocate QObjects to the heap.
I think under the idea that while you could do it fairly safely using the stack, there is no good reason why you would not want a QObject on the heap, given how easy QObject Lifecycle is in comparison to just run of the mill pointers.
I think the only relevant context to mention is that these developers were mainly accustomed to GUI development, where as I use Qt almost exclusively for console applications, which results in very linear coding requirements.
And despite all this, I do not have a good answer.
Are they correct? Are there any good reasons NOT to put a QObject
on the heap, even though it is designed to safely work there?
Thanks.