tags:

views:

95

answers:

1

Hi everyone!

I have a class looking like this:

class FakeRunner : public QObject
{
    Q_OBJECT
private:
    QProcess* proc;
public:
    FakeRunner();
    int run()
    {
        if (proc)
            return -1;
        proc = new QProcess();
        QStringList args;
        QString programName = "fake.exe";

        connect(comp, SIGNAL(started()), this, SLOT(procStarted()));
        connect(comp, SIGNAL(error(QProcess::ProcessError)), this,
                SLOT(procError(QProcess::ProcessError)));
        connect(comp, SIGNAL(finished(int, QProcess::ExitStatus)), this,
                SLOT(procFinished(int, QProcess::ExitStatus)));

        proc->start(programName, args);

        return 0;
    };

private slots:
    void procStarted() {};
    void procFinished(int, QProcess::ExitStatus) {};
    void procError(QProcess::ProcessError);
}

Since "fake.exe" does not exist on my system, proc emits the error() signal. If I handle it like following, my program crashes:

void FakeRunner::procError(QProcess::ProcessError rc)
{
    delete proc;
    proc = 0;
}

It works well, though, if I don't delete the pointer. So, the question is how (and when) should I delete the pointer to QProcess? I believe I have to delete it to avoid a memory leak. FakeRunner::run() can be invoked many times, so the leak, if there is one, will grow.

Thanks!

+2  A: 

You can't delete QObject instance inside slot which is connected to a signal in this instance using normal delete operator. This is due to the fact that if signal and slot connected using direct connection then the slot actually called from the signal implementation made by moc. This is like attempt to "delete this;" from inside the member of a class. There is a solution QObject::deleteLater(). Object will be deleted by Qt event loop inside events processing function. So you need to call proc->deleteLater() in your case.

And you don't need to disconnect signal from slot since Qt do it automatically when QObject is deleted.

VestniK
I see. Is it safe nullify the pointer after I call proc->deleteLater(), or should I use a different method to find whether the process exists (I check this at the beginning of the run() function to avoid duplicate processes)?
Kopfschmerzen
You can safely nullify your pointer after deleteLater().
VestniK