mardi 28 août 2018

Staic qobject won't destruct if having a active QTcpServer child

Here is the demo to reproduce, having a singleton Base class contains a QTcpServer child:

#include <QTcpServer>
#include <QApplication>
#include <QDebug>

class Base : public QObject
{
    Q_OBJECT
public:
    Base(Base const&)             = delete;
    Base operator=(Base const&)   = delete;
    static Base& instance() { static Base instance; return instance; }

    static void start() {
        qDebug("start");
        instance().init();
    }

private:
    void init() {
        qDebug("createSub");
        sub = new QTcpServer(this);
        sub->listen(); // ● Here is the problem
    }

    Base() = default;
    ~Base() {
        qDebug("destruct base");
    }

    QTcpServer* sub;
};

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);

    Base::start();

    return app.exec();
}

#include "main.moc"

The problem is if QTcpServer start listen, the destructor of Base won't be invoked. can comment listen to see the difference. Calling listen function makes "destruct base" will not be outputted when the program is closed.

Why does this happen?

Aucun commentaire:

Enregistrer un commentaire