c++ - 访问 QApplication::arguments 时出现段错误

标签 c++ qt qt5 qt5.5

在为 gui 编写包含 qt 的程序时,我偶然发现了一个问题,可以使用下面的最少代码重现该问题:

#include <iostream>
#include <QApplication>
#include <QSettings>

using namespace std;

int main(int argc, char ** argv) {
    QApplication *app;
    {
        int tmp_argc = argc;
        app = new QApplication(tmp_argc, argv);
    }
    QSettings settings("testvendor");
    cout<<"Num of arguments: "<<app->arguments().count()<<std::endl;
    return 0;
}

运行会导致核心转储(在对 QApplication::arguments 的调用中)或参数数量:0,这显然是错误的。

如果我使用 app = new QApplication(argc, argv) 实例化 app (使用带有参数计数的无作用域变量)或删除 的声明/定义>settings - 程序按预期输出Num of argument: 1(这些更改中的任何一项都足够)。

我在Ubuntu上使用Qt 5.5,该项目是基于cmake的,CMakeLists.txt的内容>:

cmake_minimum_required(VERSION 3.3)
project(qtest)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(CMAKE_PREFIX_PATH /opt/Qt/6.5.1/gcc_64/)
find_package(Qt5Widgets REQUIRED)

set(SOURCE_FILES main.cpp)
add_executable(qtest ${SOURCE_FILES})
target_link_libraries(qtest Qt5::Widgets)

最佳答案

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."

From QT 5 Documentation 。强调我的。

tmp_argc 超出范围。

QApplication *app;
{
    int tmp_argc = argc;
    app = new QApplication(tmp_argc, argv);
} <-- BOOM!

关于c++ - 访问 QApplication::arguments 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35566459/

相关文章:

c++ - qml 未知方法返回类型 : ArchiveFile*, 即使调用了 qmlRegisterUncreatableType

c++ - 如何让 OpenCV 成为我的 qt 项目的默认库?

javascript - JWPlayer 在 Qt5 QWebView 中不可见

c++ - 公开 QTimer。 (Qt, C++)

Python Qt : Interactive Re-Sizable QGraphicsItem, 鼠标悬停区域不调整大小

c++ - 浮点精度 - C++03

Python 的 C++ 名称修改库

qt - 在 Qt 中发布事件而不指定目标对象

c++ - 尝试在玩家死亡时切换纹理(OpenGL + C++)

c++ - 为什么 CodeBlocks 12.11 在 Windows 上用红色锯齿线在我的评论下划线,如何关闭此功能?