0

在调试时,我想出了对我来说很奇怪的事情。在主函数中,我将窗口的创建注释如下:

#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()方法,也会打印他们的消息。我尝试了clean运行ning qmakerebuild,但没有成功。这里发生了什么?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 中调用这个类。(正如我从评论中了解到的,这段代码就足够了)

4

1 回答 1

1

根据评论,我做了一个小研究,发现了这个答案:

静态成员在 main() 之前初始化,在 main() 中返回后按创建的相反顺序销毁。

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

感谢所有发表评论的人。

于 2018-04-13T03:54:24.037 回答