如何在主事件循环之前创建一些对象?

时间:2018-04-12 09:01:01

标签: c++ qt qt5 qeventloop

在调试时,我想出了一些奇怪的事情。在main函数中,我注释了窗口的创建如下:

#include <QApplication>
#include <QMetaType>
#include <QDebug>

//#include "mainwindow.h"

int main(int argc, char *argv[])
{
    qDebug() << "Creating QApplication";
    QApplication a(argc, argv);
    qDebug() << "QAplication has been created successfully";

    qDebug() << "Creating application window";
    // MainWindow w;
    qDebug() << "Displaying application window";
    // w.show();
    qDebug() << "Application window has been displayed successfully";

    return a.exec();
}

我以为我只是创建一个事件循环并进行午餐。但输出让我感到惊讶:

"17:28:32.793" ButtonControl: contructor.
"17:28:32.807" GestureControl: contructor
Creating QApplication
QAplication has been created successfully
Creating application window
Displaying application window
Application window has been displayed successfully

我有ButtonControlGestureControl类,前两行输出来自它们的构造函数。我在其他类中创建了对象,我在MainWindow类中使用它。对我来说奇怪的是它们是在MainWindow和事件循环之前/之前创建的。即使我没有创建QApplication对象并调用其exec()方法,也会打印他们的消息。我尝试了清理运行 ning qmake ,以及重建,但没有成功。这里发生了什么? ButtonControlGestureControl类有什么问题?

环境:win7,Qt 5.10,MSVC 2015。

<小时/>

修改

这是我的Control课程:

class Control : public QObject
{
    Q_OBJECT
public:
    explicit Control(QObject *parent = nullptr);
    static ButtonControl *getButtonController() {
        return &buttonController;
    }
    static GestureControl *getGestureController() {
        return &gestureController;
    }

private:
    static ButtonControl buttonController;
    static GestureControl gestureController;
};

我在MainWindow中调用此类。 (据我从评论中理解,这段代码就足够了)

1 个答案:

答案 0 :(得分:1)

发表评论后,我做了一项小型研究,发现this回答:

  

静态成员在main()之前初始化,并且在main()返回后以相反的创建顺序销毁它们。

     

静态成员是静态分配的,它们的生命周期从程序开始和结束。

感谢所有评论过的人。