How do I properly delete a QProcess instance?

I have a class that looks 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 an error () signal. If I process it like below, my program crashes:

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

      

Works well, although I am not deleting the pointer. So the question is, how (and when) should I delete the pointer to the QProcess? I believe I should remove it to avoid a memory leak. FakeRunner :: run () can be called many times, so the leak, if any, will grow.

Thanks!

+2


a source to share


1 answer


You cannot delete the instance QObject

inside the slot that is connected to the signal in this case using the normal delete operator. This is because if the signal and slot are connected using a direct connection, then the slot is actually called from the signal implementation made by moc. It's like trying delete this;

from inside a class member. There is a solution QObject::deleteLater()

. The object will be removed in the Qt event loop inside the event handling function. Therefore, you need to call proc->deleteLater()

in your case.



And you don't need to disconnect the signal from the slot, as Qt does this automatically when it QObject

is removed.

+8


a source







All Articles