Skip to content

Commit

Permalink
fix: 一个进程多次实例化QApplication程序崩溃。
Browse files Browse the repository at this point in the history
QApplication在析构时会引起DPlatformIntegration的析构,DPlatformIntegration析构会释放其静态成员变量m_xsettings。
DGuiApplicationHelper为全局变量,只会init一次,创建DPlatformTheme,
DPlatformIntegration::buildNativeSettings在new DNativeSettings时会拷贝DPlatformIntegration的m_xsettings变量,
保存在其成员变量m_settings里。
当QApplication第二次构造时,重新获取调色板,会通过DGuiApplicationHelper访问应用主题,
继而会访问到DNativeSettings指向的m_settings成员变量,
此时m_settings指向的内存已经在上一次QApplication析构时释放掉了,成为了野指针,导致程序崩溃。

在QApplication析构之后再将DGuiApplicationHelper析构,
需要时再重新构造DGuiApplicationHelper,再次init,创建DPlatformTheme,
可保证DNativeSettings跟QApplication实例化次数无关,每次都重新构造。

Log:
Change-Id: I1aaba6397124afb3b95cc46c82db0efb2999a9aa
  • Loading branch information
18202781743 committed Jun 25, 2021
1 parent 123cbb5 commit 9a89317
Showing 1 changed file with 20 additions and 6 deletions.
26 changes: 20 additions & 6 deletions src/kernel/dguiapplicationhelper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -427,14 +427,16 @@ class _DGuiApplicationHelper
{
public:
_DGuiApplicationHelper()
: helper(creator())
: helper(nullptr)
{
helper->initialize();
}

~_DGuiApplicationHelper()
{
delete helper;
if (helper) {
helper->deleteLater();
helper = nullptr;
}
}

static DGuiApplicationHelper *defaultCreator()
Expand Down Expand Up @@ -497,9 +499,8 @@ void DGuiApplicationHelper::registerInstanceCreator(DGuiApplicationHelper::Helpe
_DGuiApplicationHelper::creator = creator;

if (_globalHelper.exists() && _globalHelper->helper) {
delete _globalHelper->helper;
_globalHelper->helper = creator();
_globalHelper->helper->initialize();
_globalHelper->helper->deleteLater();
_globalHelper->helper = nullptr;
}
}

Expand All @@ -515,6 +516,19 @@ inline static int adjustColorValue(int base, qint8 increment, int max = 255)
*/
DGuiApplicationHelper *DGuiApplicationHelper::instance()
{
// 单例模式,延迟创建DGuiApplicationHelper
if (nullptr == _globalHelper->helper) {
_globalHelper->helper = _DGuiApplicationHelper::creator();
_globalHelper->helper->initialize();
// 当QApplication析构时,同时析构DGuiApplicationHelper
QObject::connect(qApp, &QObject::destroyed, [](){
if (_globalHelper->helper) {
_globalHelper->helper->deleteLater();
_globalHelper->helper = nullptr;
}
});
}

return _globalHelper->helper;
}

Expand Down

0 comments on commit 9a89317

Please sign in to comment.