[英]How some objects are created before main event loop?
在調試時,我想到了一件奇怪的事情。 在主要功能中,我對窗口的創建進行了注釋,如下所示:
#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
我有ButtonControl
和GestureControl
類和前兩行輸出的是從它們的構造。 我在MainWindow類中使用的其他類中創建它們的對象。 對我來說,奇怪的是它們是在MainWindow和事件循環之前/不創建的。 即使我不創建QApplication
對象並調用其exec()
方法,也會打印其消息。 我嘗試清理並運行 qmake ,然后重建 ,但是沒有成功。 這里發生了什么? 什么是錯的ButtonControl
和GestureControl
類?
環境: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中調用此類。 (據我所知,此代碼段就足夠了)
經過評論,我進行了一次小型研究,找到了這個答案:
靜態成員在main()之前初始化,並且在main()返回之后以創建時的相反順序銷毀它們。
靜態成員是靜態分配的,其生存期始於程序。
謝謝所有發表評論的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.