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

标签 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() 方法,它们的消息也会被打印出来。我尝试了cleaning 和running qmake,以及rebuilding,但没有成功。这里发生了什么? 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;
};

我在我的主窗口中调用这个类。 (正如我从评论中了解到的,这个代码片段就足够了)

最佳答案

根据评论,我做了一个小调查,发现 this回答:

Static members are initialized before main(), and they are destroyed in reverse order of creation after the return in main().

Static members are statically allocated, and their lifetime begins and ends with the program.

感谢所有发表评论的人。

关于c++ - 在主事件循环之前如何创建一些对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49792304/

相关文章:

c++ - 将 QLineEdit 设置为仅接受数字

qt - 在QWebEngineView中显示(youtube)视频

c++ - QTextEdit 需要越来越多的时间来绘制文本

matplotlib - Matplotlib 中的透明导航栏(或者,可以在没有栏的情况下添加导航按钮吗?)

macos - Qt 和 OpenGL OS X : GLSL shader version only 120 on Mountain Lion

javascript - 在 QML 中使用对话框

c++ - 2018 年使用 C++ 处理 Unicode 的正确方法?

c++ - 如何使用 Valgrind 和 Qt Creator 调试远程应用程序?

c++ - 在不安装 Visual Studio 的情况下使用 Microsoft C++ 编译器

c++ - 将 MFC 支持添加到 Qt 项目