堆分配的 QApplication 被删除

Heap-Allocated QApplication Getting Deleted

在基本的 C++ Qt Widgets 应用程序中,在堆栈上创建一个 QApplication 或直接在 main 函数中对其进行堆分配是可行的,但是调用堆分配的函数会 QApplication 并使用返回的指针给出了分段错误:

#include <QtWidgets>

QApplication* create_application(int argc, char* argv[]) {
    return new QApplication(argc, argv);
}

int main(int argc, char* argv[]) {
    QApplication* app = create_application(argc, argv);
    QWidget window;
    window.show();
    app->exec();
}

我认为它被自动删除了,但我不明白为什么。

问题不在于您创建具有动态存储持续时间的 QApplication,而是 QApplication 的构造函数 QApplication::QApplication(int &argc, char **argv)argc 作为参考。

还有这两个notes/warnings:

Note: argc and argv might be changed as Qt removes command line arguments that it recognizes.

Warning: The data referred to by argc and argv must stay valid for the entire lifetime of the QApplication object. In addition, argc must be greater than zero and argv must contain at least one valid character string.

您的 create_application 中对 argc 参数的引用在您退出该函数后变得无效,这违反了该警告。

如果您将 QApplication* create_application(int argc, char* argv[]) 更改为 QApplication* create_application(int &argc, char* argv[]) 它将起作用,因为 argc 现在引用 mainargc 参数并且不是副本