使用QThread和QPrinter时内存泄漏

时间:2017-01-04 10:23:04

标签: c++ qt memory-leaks qt5 qprinter

我正在使用QThread通过QPrinter

打印作品

我的PrintWorker看起来像这样:

class PrintWorker : public QObject {
    Q_OBJECT

public:
    PrintWorker(QThread*, QPrinter*, QPicture*, QPainter*, QObject *parent = 0);

private:
    QPicture *_picture = nullptr;
    QPrinter *_printer = nullptr;
    QPainter *_painter = nullptr;

    public slots:
    void print();

signals:
    void done();
};

PrintWorker::PrintWorker(QThread *thread, QPrinter *printer, QPicture *picture, QPainter *painter, QObject *parent) :QObject(parent),
_picture(picture), _printer(printer), _painter(painter)
{
    moveToThread(thread);
    QObject::connect(thread, &QThread::started, this, &PrintWorker::print);
    QObject::connect(this, &PrintWorker::done, thread, &QThread::quit);
    QObject::connect(this, &PrintWorker::done, this, &PrintWorker::deleteLater);
    QObject::connect(thread, &QThread::finished, thread, &QThread::deleteLater);
}

void PrintWorker::print() {
    // do some print job with painter and picture
    emit done();
}

print方法是这样的:

void NewService::print() {
    if (!_printer) { /* _printer : a private member */
        _printer = new QPrinter(QPrinter::HighResolution);
        _printer->setPageSize(QPrinter::A5);
        _printer->setPageOrientation(QPageLayout::Portrait);
        _printer->setColorMode(QPrinter::Color);
    }

    if (!_printDialog) { /* _printDialog : a private member */
        _printDialog = new QPrintDialog(_printer);
    }

    if (_printDialog->exec() == QPrintDialog::Accepted) {
        MyWidget *widget = new MyWidget(/* some args*/);

        QPainter *painter = new QPainter;
        QPicture *picture = new QPicture;
        widget->render(picture);

        QThread *thread = new QThread;
        PrintWorker *worker = new PrintWorker(thread, _printer, picture, painter);
        thread->start();
    }
}

现在在调用print()之前,我的应用程序在打印后调用大约9MB的内存并调用PrintWorker::print()我的应用程序的内存使用量达到26MB

在另一个世界中,如果我们在emit done的最后一部分删除PrintWorker::print(),则没有任何区别。

我们在完成工作后的期望是内存使用量应降至26MB - 线程空间+ _printer + _printDialog对象大小≈14MB

那么这有什么问题?

2 个答案:

答案 0 :(得分:0)

您要删除PrintWorkerQThread个对象,但不是QPainterQPictureMyWidgetQPrintDialogQPrinter 。这些是内存泄漏(new没有delete)。请注意,PrintWorker析构函数可以负责删除QPainterQPictureQPrinter,此外,它还可以取得MyWidget的所有权并删除它。希望QPrintDialog类删除NewService对象,但很难说代码未发布。

另外,作为rafael gonzalez的推荐,您应该检查QThread PrintWorkerQThread是否实际被删除。

顺便问一下,你是如何检查内存使用情况的?通过泄漏检测工具(如valgrind,VLD ...)?或者通过Windows任务管理器。因为任务经理肯定是不准确的。

答案 1 :(得分:0)

通过调用QThread::quit(),您将在此线程中激活退出EventLoop。驻留在此线程中的对象的QObject::deleteLater()可能不再执行(尽管他们在QThread::finished()上提及 - 表示仍将调用删除后面的插槽)。

我个人只是使​​用finished()信号设置连接,或者将worker-object的父设置为线程本身,然后Qt实际上必须删除该对象。

http://doc.qt.io/qt-5/qthread.html#exit