c++ - 处理 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。
解决方案
推荐阅读
- java - 如何在 Swing 控件中显示老挝语(语言)?
- eclipse - 删除 Git 存储库已删除我的项目
- java - 我的问题是关于java中的正则表达式
- reactjs - 无法通过 react_router4 传递状态值
- python - 如何用一个函数制作多个 lambda 函数?
- html - 用于按钮文本和类的 Selenium css 选择器
- multithreading - 在独立的 Perl 脚本中使用 Mojo::Promise
- php - Laravel 查询、分组和计数
- javascript - 如何在手机浏览器中打开具有本地 css 链接的 html 文件
- angular - ng-content 中的子组件的角度传递输入