首页 > 解决方案 > 处理 Windows Qt 应用程序中的内存耗尽

问题描述

我的应用程序可以使用大量内存,我希望能够优雅地处理内存不足。所以我这样做:

bool Application::notify( QObject* receiver, QEvent* event )
{
    bool done = true;
    try
    {
        done = QApplication::notify( receiver, event );
    }
    catch ( std::bad_alloc& ex )
    {
        releaseMemory();
        qWarning() << "bad_alloc exception: " << ex.what();
        m_outOfMemoryDlg->exec();
        exit( 1 );
    }
    catch ( const std::exception& ex )
    {
        releaseMemory();
        qWarning() << "exception: " << ex.what();
        criticalMessage( nullptr, QString( "%1 has to close due to an exception. Please contact support." ).arg( APP_NAME ) );
        exit( 2 );
    }
    catch ( ... )
    {
        releaseMemory();
        qWarning() << "exception";
        criticalMessage( nullptr, QString( "%1 has to close. Please contact support." ).arg( APP_NAME ) );
        exit( 3 );
    }
    return done;
}

其中 m_outOfMemoryDlg 是一个 QDialog,其中包含我在启动时创建和隐藏的有用消息。这一切在 macOS 上运行良好。我得到一个 std::bad_alloc 异常,出现 QDialog 并且程序正常关闭。但在 Windows 上,整个操作系统只是锁定。屏幕冻结,我必须关闭电源并重新打开才能使其响应。

在我的 .pro 文件中,我添加了:

CONFIG += exceptions

win32 {
    QMAKE_CXXFLAGS_EXCEPTIONS_ON = /EHa
    QMAKE_CXXFLAGS_STL_ON = /EHa
}

我还补充说:

#ifdef Q_OS_WIN
#include <new.h>
LONG WINAPI
exceptionFilter( struct _EXCEPTION_POINTERS* exceptionInfo )
{
    if ( exceptionInfo )
    {
        EXCEPTION_RECORD* er = exceptionInfo->ExceptionRecord;
        if ( er )
        {
            qWarning() << "Windows exception: " << er->ExceptionCode;
        }
    }
    exit( 4 );
    return EXCEPTION_EXECUTE_HANDLER;
}

int outOfMemory( size_t )
{
    qWarning() << "Out of memory";
    exit( 5 );
    return 0;
}
#endif

Application::Application( int& argc, char** argv )
: QApplication( argc, argv )
{
#ifdef Q_OS_WIN
    SetUnhandledExceptionFilter( exceptionFilter );
    _set_new_handler( outOfMemory );
#endif
...
}

根据https://www.codeproject.com/Articles/207464/Exception-Handling-in-Visual-Cplusplus。仍然没有运气。有任何想法吗?

我在 Windows 10 上使用 Qt 5.15.2。

标签: c++qtqt5out-of-memory

解决方案


推荐阅读