简体   繁体   中英

How some objects are created before main event loop?

While debugging, I came up with strange for me thing. In the main function, I commented out creation of window as follows:

#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();
}

I thought I am just creating an event loop and lunching it. But output surprised me:

"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

I have ButtonControl and GestureControl classes and first 2 lines of output are from their constructors. I create their objects inside of other class, which I use in MainWindow class. The strange thing for me is they are created before/without MainWindow and event loop. Their messages are printed even if I don't create QApplication object and call its exec() method. I tried clean ing and run ning qmake , and rebuild ing, but no success. What's going on here? What is wrong with ButtonControl and GestureControl classes?

Env: win7, Qt 5.10, MSVC 2015.


Edit

Here is my Control class:

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;
};

I call this class inside my MainWindow. (As I understand from comments this code snippet is enough)

Following comments, I did a small research and found this answer:

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.

Thank you everyone who commented out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM