http://doc.qt.digia.com/qt/qhboxlayout.html#detailsから取得したこのコード スニペットは、私が認識していない魔法を除いて、潜在的なメモリ リークでいっぱいです。
編集:ここに見られるように、例外の安全性がQtで奇妙であることを指摘してくれたNikos C.に感謝します: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();
最後の 2 行より前の例外はすべてをリークします (実際のコードではウィンドウに親があると仮定します)。
同様の Qt 以外のコードでは、sentry オブジェクトを使用してこの種の処理を行います。私のコードを見たときに他の人が理解できる、ここで歩哨を使用するベストプラクティスの方法はありますか?
編集:これは受け入れられるデザインパターンでしょうか?
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();