gpt4 book ai didi

c++ - 哨兵 QWidget 是个好主意吗(在创建和填充布局时防止内存泄漏)?

转载 作者:太空宇宙 更新时间:2023-11-04 12:02:07 28 4
gpt4 key购买 nike

这段代码摘自 http://doc.qt.digia.com/qt/qhboxlayout.html#details是的,除了一些我不知道的魔法,充满了潜在的内存泄漏。

编辑:感谢 Nikos C. 指出 Qt 中的异常安全性很奇怪,如下所示:http://doc.qt.digia.com/qt/exceptionsafety.html因此,为了保持我的问题的主要意图有效,我更新了示例代码:

 QWidget *window = new QWidget;
QPushButton *button1 = new QPushButton("One");
QPushButton *button2 = new QPushButton("Two");
QPushButton *button3 = new QPushButton("Three");
QPushButton *button4 = new QPushButton("Four");
QPushButton *button5 = new QPushButton("Five");

QMyWidgetThatCanThrow *myWidget = new QMyWidgetThatCanThrow("");

QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(button1);
layout->addWidget(button2);
layout->addWidget(button3);
layout->addWidget(button4);
layout->addWidget(button5);
layout->addWidget(myWidget);

window->setLayout(layout);
window->show();

只有在最后才将小部件重新分配给窗口,因此最后两行之前的任何异常都会泄漏所有内容(假设在真实代码中窗口有一个父窗口)。

在类似的非 Qt 代码中,我会使用哨兵对象来处理这种事情。是否有其他人在查看我的代码时会理解的使用哨兵的最佳实践方法?

编辑:这是可接受的设计模式吗?

void PopulateWindow(QWidget *window)
{
QWidget sentry; //serves as the intial parent ensuring that all
//widgets are either reparented or deleted
QPushButton *button1 = new QPushButton("One",&sentry);
QPushButton *button2 = new QPushButton("Two",&sentry);
QPushButton *button3 = new QPushButton("Three",&sentry);
QPushButton *button4 = new QPushButton("Four",&sentry);
QPushButton *button5 = new QPushButton("Five",&sentry);

QHBoxLayout *layout = new QHBoxLayout(&sentry);
layout->addWidget(button1);
layout->addWidget(button2);
layout->addWidget(button3);
layout->addWidget(button4);
layout->addWidget(button5);

window->setLayout(layout);
} //sentry goes out of scope and deletes anything that was not reparented

使用它:

 QWidget *window = new QWidget;
PopulateWindow(window);
window->show();

最佳答案

什么地方可能出错?你想避免什么问题?如果你创建了小部件并且有任何东西迫使你中止,就像你在常规 C/C++ 中做的那样

if(huhOh!!){
delete button1;
delete button2;
....
return false
}

编辑:

没有什么能阻止你做

void PopulateWindow(QWidget *window){

QPushButton *button1 = new QPushButton("One",window);
QPushButton *button2 = new QPushButton("Two",window);
QPushButton *button3 = new QPushButton("Three",window);
QPushButton *button4 = new QPushButton("Four",window);
QPushButton *button5 = new QPushButton("Five",window);

QHBoxLayout *layout = new QHBoxLayout(window);
layout->addWidget(button1);
layout->addWidget(button2);
layout->addWidget(button3);
layout->addWidget(button4);
layout->addWidget(button5);

//layout already set
//window->setLayout(layout);
}

在这种情况下,您只需删除 window

关于c++ - 哨兵 QWidget 是个好主意吗(在创建和填充布局时防止内存泄漏)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13703970/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com