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?

demonplus
  • 5,613
  • 12
  • 49
  • 68
zar
  • 11,361
  • 14
  • 96
  • 178
  • 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. – Igor Tandetnik Aug 27 '15 at 15:02
  • @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? – zar Aug 27 '15 at 15:15
  • 2
    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). – Igor Tandetnik Aug 27 '15 at 15:17

2 Answers2

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://stackoverflow.com/a/19332239/841330 RobbieE's answer is really good.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Chase Henslee
  • 3,918
  • 1
  • 18
  • 21
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()) );
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
ratchet freak
  • 47,288
  • 5
  • 68
  • 106