C++ 如何在主事件循环之前创建一些对象?
在调试时,我想出了一个奇怪的东西。在main函数中,我对窗口的创建进行了如下注释:C++ 如何在主事件循环之前创建一些对象?,c++,qt,qt5,qeventloop,C++,Qt,Qt5,Qeventloop,在调试时,我想出了一个奇怪的东西。在main函数中,我对窗口的创建进行了如下注释: #include <QApplication> #include <QMetaType> #include <QDebug> //#include "mainwindow.h" int main(int argc, char *argv[]) { qDebug() << "Creating QApplication"; QApplication
#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();
}
我有ButtonControl
和GestureControl
类,前两行输出来自它们的构造函数。我在另一个类中创建它们的对象,我在MainWindow类中使用这个类。对我来说奇怪的是,它们是在主窗口和事件循环之前/之后创建的。即使我没有创建QApplication
对象并调用其exec()
方法,它们的消息也会被打印出来。我尝试了清理和跑步,但是没有成功。这是怎么回事?按钮控制
和手势控制
类有什么问题
环境:win7,Qt 5.10,MSVC 2015。
编辑 这是我的
控件
类:
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;
};
我在主窗口中调用这个类。(据我从评论中了解,这段代码就足够了)在下面的评论中,我做了一个小调查,找到了答案: 静态成员在main()之前初始化,并在main()中返回后按与创建相反的顺序销毁 静态成员是静态分配的,其生命周期以程序开始和结束
谢谢大家的评论。也许QT中有一些静态实例?如果没有看到类的代码,我们怎么知道?请发布一个。是的,它们是
控件
类中的静态类。但是我也不创建Control
对象。静态类实例是在动态初始化阶段自动创建的,这通常发生在main
启动之前。只需在按钮Control:constructor
内设置断点,检查堆栈跟踪。
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;
};