Does Qt applications have automatic garbage collection?
Asked Answered
F

2

8

I am researching this but I don't see a conclusive answer. Does a Qt widget application clean up the memory when it exits? Does it make any difference deriving from QObject? If there is garbage collection than why is there QSharedPointer class? I am asking from the following context of my code.

void MainWindow::sync()
{
    QString destPathUnixStyle = makePathUnix( _RootPath );

    QString rsync_cmd = QString("rsync/rsync -a root@%1:/data/ '%2'").arg( _ip ).arg( destPathUnixStyle );

    QProcess *syncProcess = new QProcess(this);
    syncProcess->start( rsync_cmd );

    qDebug() << "Sync started..";

    connect(syncProcess, SIGNAL(finished(int)), this, SLOT(syncFinished()) );

    _syncInProgress = true;
}

Now will my syncProcess be cleaned up when application exits? What if user calls this function a thousand times without exiting, will it be creating memory leak?

Update

Given that my function above is called frequently many many times, is it better to declare the QProcess a member variable or just used QSharedPointerto improve the code above?

Freedwoman answered 27/8, 2015 at 14:58 Comment(3)
Qt doesn't have garbage collection. It has a concept of ownership. With new QProcess(this);, you made the new QProcess object owned by this instance of MainWindow. When a QObject is destroyed, it in turn destroys all objects it owns.Hooghly
@IgorTandetnik since my function is called repeatedly, will it collect memory during a single run of execution? Should I instead use QSharedPointer or make QProcess a member variable?Freedwoman
You could explicitly destroy it in finished handler, I suppose. QObject::deleteLater is convenient for this (it avoids deleting an object while in that object's signal).Hooghly
J
11

Qt does not use garbage collection, instead it uses reference counting (in the case of QSharedPointers) and object ownership (in the case of your example).

In your case, The QProcesses will be destroyed when your MainWindow class is destroyed.

edit: https://mcmap.net/q/555730/-how-does-qt-delete-objects-and-what-is-the-best-way-to-store-qobjects-duplicate RobbieE's answer is really good.

Joaquin answered 27/8, 2015 at 15:11 Comment(0)
P
3

Qt handles an "ownership" tree structure. A QObject may have a set of children and if it gets deleted then it will delete all of its children.

In your code the syncProcess will get deleted when the this that you passed gets deleted or when it explicitly gets deleted.

You can let it delete itself after it sends the signal by connecting the finished signal to its own deleteLater slot.:

connect(syncProcess, SIGNAL(finished(int)), syncProcess, SLOT(deleteLater()) );
Pops answered 27/8, 2015 at 15:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.